Reading Text Lines Using a Functional Stream
The lines() method of the Files class creates a stream that can be used to read the lines in a text file. It is efficient as it does not read the whole file into memory, making available only one line at a time for processing. Whereas the BufferedReader class provides an analogous method that uses a BufferedReader, the stream created by the Files.lines() method is backed by a more efficient FileChannel.
static Stream<String> lines(Path path) throws IOException
static Stream<String> lines(Path path, Charset cs) throws IOException
Return a Stream of type String, where the elements are text lines read from a file denoted by the specified path. The first method decodes the bytes into characters using the UTF-8 charset. The charset to use can be explicitly specified, as in the second method.
As an example of using the lines() method, we implement the solution to finding palindromes (ยง13.3, p. 688), where the words are read from a file.
Path wordFile = Path.of(“.”, “project”, “wordlist.txt”);
System.out.println(“Find palindromes, greater than length 2.”);
try (Stream<String> stream = Files.lines(wordFile)){
List<String> palindromes = stream
.filter(str -> str.length() > 2)
.filter(str -> str.equals(new StringBuilder(str).reverse().toString()))
.toList();
System.out.printf(“List of palindromes: %s%n”, palindromes);
System.out.printf(“Number of palindromes: %s%n”, palindromes.size());
} catch (IOException e) {
e.printStackTrace();
}
Possible output from the code (edited to fit on the page):
Find palindromes, greater than length 2.
List of palindromes: [aba, abba, aga, aha, …]
Number of palindromes: 90
The following code creates a map to count the number of lines with different lengths:
Path textFile = Path.of(“.”, “project”, “linesOnly.txt”);
try (Stream<String> stream = Files.lines(textFile)) {
Map<Integer, Long> grpMap =
stream.collect(Collectors.groupingBy(String::length,
Collectors.counting()));
System.out.println(grpMap);
} catch (IOException e) {
e.printStackTrace();
}
Possible output from the code:
{4=1, 21=2, 10=1, 12=1}