首页 > 解决方案 > 为什么 BufferedReader::readLine 挂在 EOF 上?

问题描述

我有一些 Java 8 代码试图将文件的内容(包括换行符)读入一个字符串;这是胆量:

static private void fn( BufferedReader reader ) throws IOException {
    StringBuilder builder = new StringBuilder( 1000000 );
    String line = null;
    while ( ( line = reader.readLine() ) != null ) {
        builder.append( line ).append( '\n' );
        System.err.println( line );
    }
    String text = builder.toString();
    ...
}

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
    fn( reader );
}

我在 Eclipse 中的运行配置下运行它,它System.in从一个文件(它确实以 EOF 结尾)重定向,并且打印语句确认这些行确实被读取,但是一旦读取超过最后一行,它挂在 Eclipse 调试器中。

以这种方式从其他文件中读取我没有遇到这个问题;为什么现在?

标签: javafile-io

解决方案


推荐阅读