Text file into Java List using Commons or Guava

前端 未结 7 541
灰色年华
灰色年华 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 01:52

    This is probably what youre looking for

    FileUtils.readLines(File file)

    0 讨论(0)
  • 2021-01-08 01:57

    Here's how to do it with Guava:

    List<String> lines = Files.readLines(new File("myfile.txt"), Charsets.UTF_8);
    

    Reference:

    • Files.readLines(File, Charset)
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-08 02:06

    Using Apache Commons IO, you can use FileUtils#readLines method. It is as simple as:

    List<String> lines = FileUtils.readLines(new File("..."));
    for (String line : lines) {
      System.out.println(line);  
    }
    
    0 讨论(0)
  • 2021-01-08 02:08

    They are pretty similar, with Commons IO it will look like this:

    List<String> lines = FileUtils.readLines(new File("file.txt"), "UTF-8");
    

    Main advantage of Guava is the specification of the charset (no typos):

     List<String> lines = Files.readLines(new File("file.txt"), Charsets.UTF_8);
    
    0 讨论(0)
  • 2021-01-08 02:08

    I'm not sure if you only want to know how to do this via Guava or Commons IO, but since Java 7 this can be done via java.nio.file.Files.readAllLines(Path path, Charset cs) (javadoc).

    List<String> allLines = Files.readAllLines(dir.toPath(), StandardCharsets.UTF_8);
    

    Since this is part of the Java SE it does not require you to add any additional jar files (Guava or Commons) to your project.

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