Java: reading trailing newline from a text file

How can you get the contents of a text file while maintaining the presence of a new line at the end of the file? Using this technique, it is impossible to determine if a file ends on a new line:

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");
}
+5
source share
2 answers

You can read the entire contents of the file using one of the methods listed here.

My favorite is this one:

public static long copyLarge(InputStream input, OutputStream output)
       throws IOException {
   byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
   long count = 0;
   int n = 0;
   while ((n = input.read(buffer))>=0) {
       output.write(buffer, 0, n);
       count += n;
   }
   return count;

}

0
source

readLine(); , read(). BufferedReader, , "" CR/LF Windows.

+7

All Articles