简体   繁体   English

Java:从文本文件中读取尾随的新行

[英]Java: Reading the Trailing New Line from a Text File

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");
}

Don't use readLine(); 不要使用readLine(); transfer the contents one character at a time using the read() method. 使用read()方法一次传输一个字符的内容。 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. 如果你在BufferedReader上使用它,它将具有相同的性能,虽然与上面的代码不同,它不会“规范化”Windows风格的CR / LF换行符。

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;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM