Java实现获取文本文件中特定字符串最后一次出现的行
Fixing Java Code to Find the Last Occurrence of a String in a Text File
Hey there! Let's refine your code to properly find the last line containing a specific search string in your log file. Your current snippet has a few gaps (like skipping the first line and incomplete match logic) — here's a complete, robust version:
Complete Working Code
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class LastOccurrenceFinder { public static void main(String[] args) { // Define your target log file path String filePath = "C:\\Users\\prudra\\Desktop\\Axalta\\20180406114505\\activemq.log_app1"; // Get user input for the string to search Scanner inputScanner = new Scanner(System.in); System.out.print("Enter the string you want to search for: "); String searchString = inputScanner.nextLine(); // Variables to track the last matching line details String lastMatchingLine = null; int lastMatchingLineNumber = -1; int currentLineNumber = 0; // Use try-with-resources to auto-manage file scanner resources try (Scanner fileScanner = new Scanner(new File(filePath))) { while (fileScanner.hasNextLine()) { currentLineNumber++; String line = fileScanner.nextLine(); // Update tracking variables only when a match is found if (line.contains(searchString)) { lastMatchingLine = line; lastMatchingLineNumber = currentLineNumber; } } // Output the final result if (lastMatchingLine != null) { System.out.println("\nLast occurrence found at line " + lastMatchingLineNumber); System.out.println("Line content: " + lastMatchingLine); } else { System.out.println("\nThe search string was not found in the file."); } } catch (FileNotFoundException e) { System.err.println("Error: Could not locate the file at path: " + filePath); e.printStackTrace(); } finally { inputScanner.close(); } } }
Key Improvements & Explanations
- No Line Skipping: Your original code called
file.nextLine()before the loop, which skipped the first line of the file. We removed this to ensure every line is checked. - Track Last Match: Instead of just counting lines, we keep updating our tracking variables every time a match is found — this guarantees we end up with the very last occurrence.
- Safe Resource Handling: The
try-with-resourcesblock automatically closes the file scanner when done, preventing memory leaks and manual cleanup errors. - Error Resilience: Added a
FileNotFoundExceptioncatch block to handle cases where the file is missing or inaccessible. - Clean Input Flow: Separated user input handling and ensured the input scanner is closed properly in the
finallyblock.
Note: The original snippet included a question about environment selection (Dev/QA/Prod) — if that's part of your workflow, you can add logic to switch file paths based on the selected environment, but it wasn't necessary for the core task of finding the last matching line.
内容的提问来源于stack exchange,提问作者brucewayne
相关产品推荐
相关产品推荐

