logo

Java Streams 101, how to read text file

Java Streams tutorial, how to read text file using BufferedReader and FileReader in Java

How to write something into a text file? The most generic way is by using streams. There are character and binary streams. Character streams extend classes Reader or Writer. Reader reads some data, writer writes some data. Binary streams extend classes InputStream or OutputStream. InputStream reads some data, OutputStream writes some data. In practice, you don't use these generic classes, but the descendants. Furthermore each stream is as easy as it gets, so you are forced to combine them together.

For example FileReader reads characters from some file, but it cannot read the whole line. BufferedReader can do that (and more). So if you combine them, you can read a file one line at a time. FileWriter can write characters into some file, but you would have to put a line separator into a file yourself. BufferedWriter has a method newLine() which writes line separator into a file.

FileReader fileReader = new FileReader("file.txt");
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();

comments powered by Disqus

rss

Free online Java web application examples

Want to develop whole web applications which use database, security and more? See my github account, where are lot's of example projects:
github

Search