Monday Feb 03, 2014

BufferedReader.lines

BufferedReader.lines is kind of interesting, letting you turn a BufferedReader into a java.util.Stream in Java 8. Here's some small experiments.

Print out the number of lines in a file:

public static void main(String[] args) {
    try (BufferedReader reader = Files.newBufferedReader(
            Paths.get("myfile.txt"),
            StandardCharsets.UTF_8)) {
        System.out.println(reader.lines().count());
    } catch (IOException ex) {
    }
}

Print out all the lines:

public static void main(String[] args) {
    try (BufferedReader reader = Files.newBufferedReader(
            Paths.get("myfile.txt"),
            StandardCharsets.UTF_8)) {
        reader.lines().forEach(System.out::println);
    } catch (IOException ex) {
    }
}

Print out the longest line in a file:

public static void main(String[] args) {
    try (BufferedReader reader = Files.newBufferedReader(
            Paths.get("myfile.txt"),
            StandardCharsets.UTF_8)) {
        System.out.println(reader
                .lines()
                .mapToInt(String::length)
                .max()
                .getAsInt());
    } catch (IOException ex) {
    }
}
About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« February 2014 »
SunMonTueWedThuFriSat
      
8
9
15
16
19
22
23
27
 
       
Today