I was confused when I want to get the last line of a plain text file in Java. How can I do this? and which is the best way without using scanner?
Thanks
In Java, we can use the Apache Commons IO ReversedLinesFileReader to read the last few lines of a File .
The Java error message Reached End of File While Parsing results if a closing curly bracket for a block of code (e.g, method, class) is missing. The fix is easy — just proofread your code.
In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
To read the line and move on, we should use the nextLine() method. This method advances the scanner past the current line and returns the input that wasn't reached initially. This method returns the rest of the current line, excluding any line separator at the end of the line.
The simplest way to do it is simply to iterate over the lines in the file and stop when you reach the end. For example:
// I assume this is disposed properly etc
private static String getLastLine(BufferedReader reader) throws IOException {
String line = null;
String nextLine;
while ((nextLine = reader.readLine()) != null) {
line = nextLine;
}
return line;
}
This will return null for an empty reader.
Unless I knew I was going to have to read a really big file, that's what I'd do. Trying to do this by skipping straight to the last line is hard. Really hard, especially if you need a variable-width encoding such as UTF-8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With