Reading a text file in Java
File handling has become easy in Java. In this post we will see how to read the file contents as stream of strings and to print the contents from the streams. We will be using lines method from Files class.
public class ReadFileAsStream {
private static String fileName = "D:\\proverbs.txt";
public static void main(String args[]) {
Path path = Paths.get(fileName);
Stream<String> contents = null;
try {
contents = Files.lines(path);
contents.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
} finally {
contents.close();
}
}
}
Output:
Practice makes perfect
You are never to old to learn
Don’t put off until tomorrow what you can do today
Life is what you make it
Leave a Reply