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

前端 未结 21 2384
心在旅途
心在旅途 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:10

    In Java 8, there is also an alternative to using Files.lines(). If your input source isn't a file but something more abstract like a Reader or an InputStream, you can stream the lines via the BufferedReaders lines() method.

    For example:

    try (BufferedReader reader = new BufferedReader(...)) {
      reader.lines().forEach(line -> processLine(line));
    }
    

    will call processLine() for each input line read by the BufferedReader.

提交回复
热议问题