BufferedReader: read multiple lines into a single string

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

    If you just want to read the entirety of a file into a string, I suggest you use Guava's Files class:

    String text = Files.toString("filename.txt", Charsets.UTF_8);
    

    Of course, that's assuming you want to maintain the linebreaks. If you want to remove the linebreaks, you could either load it that way and then use String.replace, or you could use Guava again:

    List lines = Files.readLines(new File("filename.txt"), Charsets.UTF_8);
    String joined = Joiner.on("").join(lines);
    

提交回复
热议问题