How can I read a large text file line by line using Java?

前端 未结 21 2350
心在旅途
心在旅途 2020-11-21 05:48

I need to read a large text file of around 5-6 GB line by line using Java.

How can I do this quickly?

相关标签:
21条回答
  • 2020-11-21 06:33

    In Java 8, you could do:

    try (Stream<String> lines = Files.lines (file, StandardCharsets.UTF_8))
    {
        for (String line : (Iterable<String>) lines::iterator)
        {
            ;
        }
    }
    

    Some notes: The stream returned by Files.lines (unlike most streams) needs to be closed. For the reasons mentioned here I avoid using forEach(). The strange code (Iterable<String>) lines::iterator casts a Stream to an Iterable.

    0 讨论(0)
  • 2020-11-21 06:33

    You need to use the readLine() method in class BufferedReader. Create a new object from that class and operate this method on him and save it to a string.

    BufferReader Javadoc

    0 讨论(0)
  • 2020-11-21 06:35

    You can also use Apache Commons IO:

    File file = new File("/home/user/file.txt");
    try {
        List<String> lines = FileUtils.readLines(file);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    0 讨论(0)
提交回复
热议问题