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

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

    Once Java 8 is out (March 2014) you'll be able to use streams:

    try (Stream lines = Files.lines(Paths.get(filename), Charset.defaultCharset())) {
      lines.forEachOrdered(line -> process(line));
    }
    

    Printing all the lines in the file:

    try (Stream lines = Files.lines(file, Charset.defaultCharset())) {
      lines.forEachOrdered(System.out::println);
    }
    

提交回复
热议问题