Text file into Java List using Commons or Guava

前端 未结 7 635
灰色年华
灰色年华 2021-01-08 01:18

What is the most elegant way to put each line of text (from the text file) into LinkedList (as String object) or some other collection, using Commons or Guava libraries.

7条回答
  •  情书的邮戳
    2021-01-08 02:04

    You can use Guava:

    Files.readLines(new File("myfile.txt"), Charsets.UTF_8);
    

    Or apache commons io:

    FileUtils.readLines(new File("myfile.txt"));
    

    I'd say both are equally elegant.

    Depending on your exact use, assuming the "default encoding" might be a good idea or not. Either way, personally I find it good that the Guava API makes it clear that you're making an assumption about the encoding of the file.

    Update: Java 7 now has this built in: Files.readAllLines(Path path, Charset cs). And there too you have to specify the charset explicitly.

提交回复
热议问题