6

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");
}
Kevin Albrecht
  • 6,974
  • 7
  • 44
  • 56
  • If you are using a BufferedWriter, you could also use the .newline method: http://stackoverflow.com/questions/9199216/strings-written-to-file-do-not-preserve-line-breaks – Christian Vielma Feb 09 '16 at 11:40

2 Answers2

7

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.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
0

You can read the whole file content using one of the techniques 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;

}

Community
  • 1
  • 1
OscarRyz
  • 196,001
  • 113
  • 385
  • 569