1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
package com.read.file; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; public class MyFileReader { public static void main(String[] args) { Path file = Paths.get("C:\\Users\\akumaras\\workspace\\test\\src\\com\\read\\file\\readme.txt"); try { //Java 8: Stream class Stream<String> lines = Files.lines( file, StandardCharsets.UTF_8 ); for( String line : (Iterable<String>) lines::iterator ) { System.out.println("read=" + line); } } catch (Exception e){ e.printStackTrace(); } } } |
Output:
|
|
read=A big brown fox read=jumped over the fence |
#1 double colon notation ::
The new double colon (::) operator that Java 8 has to convert a normal method into lambda expression. So,
Instead of:
|
|
list.forEach(n -> System.out.println(n)); |
You can do:
|
|
list.forEach(System.out::println); |
#2 Why is stream::iterator used?
…
Read more ›