Non-blocking (NIO) reading of lines

前端 未结 9 844
滥情空心
滥情空心 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:42

    Oracle introduces a example in the tutorial. https://docs.oracle.com/javase/tutorial/essential/io/file.html#streams

    Path file = ...;
    try (InputStream in = Files.newInputStream(file);
        BufferedReader reader =
          new BufferedReader(new InputStreamReader(in))) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException x) {
        System.err.println(x);
    }
    

提交回复
热议问题