BufferedReader:将多行读入单个字符串

S_W*_*lan 14 java text-processing bufferedreader

我正在使用BufferedReader从txt文件中读取数字进行分析.我现在的方式是 - 使用.readline读取一行,使用.split将此字符串拆分为一个字符串数组

public InputFile () {
    fileIn = null;

    //stuff here

    fileIn = new FileReader((filename + ".txt"));
    buffIn = new BufferedReader(fileIn);


    return;
    //stuff here
}
Run Code Online (Sandbox Code Playgroud)
public String ReadBigStringIn() {
    String line = null;

    try { line = buffIn.readLine(); }
    catch(IOException e){};

    return line;
}
Run Code Online (Sandbox Code Playgroud)
public ProcessMain() {
    initComponents();
    String[] stringArray;
    String line;

    try {
        InputFile stringIn = new InputFile();
        line = stringIn.ReadBigStringIn();
        stringArray = line.split("[^0-9.+Ee-]+"); 
        // analysis etc.
    }
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但如果txt文件有多行文本怎么办?有没有办法输出一个长字符串,或者可能是另一种方法呢?也许用while(buffIn.readline != null) {}?不知道如何实现这一点.

感谢赞赏,谢谢.

Paŭ*_*ann 27

你是对的,这里需要一个循环.

通常的习惯用法(仅使用普通的Java)是这样的:

public String ReadBigStringIn(BufferedReader buffIn) throws IOException {
    StringBuilder everything = new StringBuilder();
    String line;
    while( (line = buffIn.readLine()) != null) {
       everything.append(line);
    }
    return everything.toString();
}
Run Code Online (Sandbox Code Playgroud)

这将删除换行符 - 如果要保留换行符,请不要使用该readLine()方法,而只需读入char[](而将其附加到StringBuilder).

请注意,此循环将一直运行直到流结束(并且如果它没有结束将阻塞),因此如果您需要不同的条件来完成循环,请在那里实现它.


Grz*_*jos 6

我强烈建议在这里使用库,但从 Java 8 开始,您也可以使用流来做到这一点。

    try (InputStreamReader in = new InputStreamReader(System.in);
         BufferedReader buffer = new BufferedReader(in)) {
        final String fileAsText = buffer.lines().collect(Collectors.joining());
        System.out.println(fileAsText);
    } catch (Exception e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

您还可以注意到,它在内部joining使用时非常有效StringBuilder

  • 如果要保留行结尾,可以添加 System.lineSeparator() 作为 Collectors.joining 的参数: buffer.lines().collect( Collectors.joining( System.lineSeparator() ) ) (2认同)