Non-blocking (NIO) reading of lines

前端 未结 9 842
滥情空心
滥情空心 2020-12-31 07:01

I need to read a file line by line using java.nio, but nio doesn\'t have a method like readline() to read one, complete line at a time

9条回答
  •  春和景丽
    2020-12-31 07:50

    Using java.nio.file.Files you can do:

    Path path = FileSystems.getDefault().getPath("/path/to", "file.txt");
    Files.lines(path).forEach(line ->
        // consume line
    );
    

    As the lines(path) method returns a Stream, you can take advantage of any other method of the Stream API, like reading just the first line (if one exists) with:

    Optional firstLine = Files.lines(path).findFirst();
    

提交回复
热议问题