Java:从文本文件中读取尾随的新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/554266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Reading the Trailing New Line from a Text File
提问by Kevin Albrecht
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");
}
采纳答案by OscarRyz
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;
}
}
回答by Michael Borgwardt
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.
不要使用 readLine(); 使用 read() 方法一次传输一个字符的内容。如果您在 BufferedReader 上使用它,它将具有相同的性能,尽管与上面的代码不同,它不会“规范化”Windows 样式的 CR/LF 换行符。

