【问题标题】:Java: Reading the Trailing New Line from a Text FileJava:从文本文件中读取尾随新行
【发布时间】:2010-10-07 22:39:24
【问题描述】:

如何在获取文本文件内容的同时保留文件末尾是否有换行符?使用这种技术,无法判断文件是否以换行符结尾:

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

【问题讨论】:

标签: java file-io


【解决方案1】:

不要使用 readLine();使用 read() 方法一次传输一个字符。如果您在 BufferedReader 上使用它,这将具有相同的性能,但与上面的代码不同,它不会“规范化”Windows 样式的 CR/LF 换行符。

【讨论】:

    【解决方案2】:

    您可以使用here 列出的技术之一阅读整个文件内容

    我最喜欢的是这个:

    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;
    

    }

    【讨论】:

      猜你喜欢
      • 2016-07-14
      • 2015-11-26
      • 2013-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-07
      相关资源
      最近更新 更多