BufferedReader: read multiple lines into a single string

后端 未结 7 1109
逝去的感伤
逝去的感伤 2021-01-17 11:22

I\'m reading numbers from a txt file using BufferedReader for analysis. The way I\'m going about this now is- reading a line using .readline, splitting this string into an a

相关标签:
7条回答
  • 2021-01-17 11:56

    You are right, a loop would be needed here.

    The usual idiom (using only plain Java) is something like this:

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

    This removes the line breaks - if you want to retain them, don't use the readLine() method, but simply read into a char[] instead (and append this to your StringBuilder).

    Please note that this loop will run until the stream ends (and will block if it doesn't end), so if you need a different condition to finish the loop, implement it in there.

    0 讨论(0)
提交回复
热议问题