Java Read File Example

In this example I will show you how to read from a file using the Java programming language.

Java read file

The following example shows you how to read a file line by line. This approach is safe for reading large text files, because only one line is loaded into memory at the same time. Although there are multiple ways of reading files in Java, this example will work good on new as well as on early Java versions.




FileReader fr = null;
BufferedReader br = null;
try {
	fr = new FileReader("file.txt");
	br = new BufferedReader(fr);
	String line;
	while ((line = br.readLine()) != null) {
		// process the line
		System.out.println(line);
	}
} catch (FileNotFoundException e) {
	System.err.println("Can not find specified file!");
	e.printStackTrace();
} catch (IOException e) {
	System.err.println("Can not read from file!");
	e.printStackTrace();
} finally {
	if (br != null) try { br.close(); } catch (IOException e) { /* ensure close */ }
	if (fr != null) try { fr.close(); } catch (IOException e) { /* ensure close */ }
}

Closing streams is important in Java. For this reason I have included  a proper exception handling in this example.

Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+Digg thisPin on PinterestShare on RedditShare on StumbleUponPrint this pageEmail this to someone

Leave a Reply