BufferedReader: read multiple lines into a single string

后端 未结 7 1106
逝去的感伤
逝去的感伤 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:43

    I would strongly advice using library here but since Java 8 you can do this also using streams.

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

    You can notice also that it is pretty effective as joining is using StringBuilder internally.

提交回复
热议问题