Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Reading the Trailing New Line from a Text File

Tags:

java

file-io

How can you get the contents of a text file while preserving whether or not it has a newline at the end of the file? Using this technique, it is impossible to tell if the file ends in a newline:

BufferedReader reader = new BufferedReader(new FileReader(fromFile));
StringBuilder contents = new StringBuilder();

String line = null;
while ((line=reader.readLine()) != null) {
  contents.append(line);
  contents.append("\n");
}
like image 640
Kevin Albrecht Avatar asked Feb 16 '09 19:02

Kevin Albrecht


People also ask

How do you read the next line in a file in Java?

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.

Does Java readLine include newline?

Does Java readLine include newline? In Java, readLine() uses \n and \r as line feed and carriage return end characters to determine the next lines. So, when you use readLine() , then you won't get \n or \r characters to be displayed in the console as these characters will be masked by the readLine() .

How do you move to the next line in a text file in Java?

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.

Does readLine read newline?

The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end. This method returns the empty string when it reaches the end of the file.


1 Answers

Don't use readLine(); transfer the contents one character at a time using the read() method. If you use it on a BufferedReader, this will have the same performance, although unlike your code above it will not "normalize" Windows-style CR/LF line breaks.

like image 106
Michael Borgwardt Avatar answered Oct 06 '22 01:10

Michael Borgwardt