Non-blocking (NIO) reading of lines

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

    1) You could convert a BufferedReader to a Stream using the lines method

    List<String> list = new ArrayList<>();
    
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        list = br.lines().collect(Collectors.toList());    
    }
    

    2) Get a Stream directly using the Files.lines method:

    try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
        stream
            .filter(s -> s.endswith("/"))
            .map(String::toUpperCase)
            .forEach(System.out::println);
    }
    

    As DanielBraun points out in his answer, you could also use the readAllLines method instead of the lines method, difference being, straight from the docs:

    Unlike readAllLines, this method does not read all lines into a List, but instead populates lazily as the stream is consumed.

    The package summary page from Java docs gives a nice and concise overview about Streams, and this article also lists out a few other ways of reading a file by line in Java.

    0 讨论(0)
  • 2020-12-31 07:55

    Why? NIO doesn't support reading lines. You can read millions of lines a second with BufferedReader.readLine(). I suggest that is sufficient.

    0 讨论(0)
  • 2020-12-31 07:57

    In support of EJP and others above, you might reference this article: http://www.javaworld.com/article/2078654/java-se/java-se-five-ways-to-maximize-java-nio-and-nio-2.html

    In particular: "While NIO is often promoted for its performance advantages, it's more precise to say it is highly responsive. In some cases NIO actually performs worse than basic Java I/O. For simple sequential reads and writes of small files, for instance, a straightforward streams implementation might be two or three times faster than the corresponding event-oriented channel-based coding. Also, non-multiplexed channels -- that is, channels in separate threads -- can be much slower than channels that register their selectors in a single thread."

    I would highlight the statement that NIO In some cases [...] performs worse than basic Java I/O. The author follows up with a list of questions to drive a quick analysis of whether NIO is the right choice. If you (or the next person to come along) still decides to pursue NIO there is a good explanation of its use with code example.

    0 讨论(0)
提交回复
热议问题