HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

How to read file in java

By Lokesh Gupta | Filed Under: Java I/O

A file in java can be read by N number of ways. Find below some good ways to read a file in java.

Table of Contents

Read file with BufferedReader
Read file with try-with-resources
Read file with java.nio.file.Files
Read file with Apache Commons IOUtils
Read file with Guava

  1. Read file with BufferedReader

    A most simple, commonly used and efficient method used for long time with BufferedReader.

    public void readFileWithBufferedReader(String fileName) 
    {
    	BufferedReader br = null;
    	try {
    		String sCurrentLine;
    		br = new BufferedReader ( new FileReader( fileName ) );
    		while ((sCurrentLine = br.readLine()) != null) 
    		{
    			System.out.println(sCurrentLine);
    		}
    	} catch (IOException e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			//Do not forget to close the stream
    			if (br != null)
    				br.close();
    		} catch (IOException ex) {
    			ex.printStackTrace();
    		}
    	}
    }
    
  2. Read file with try-with-resources

    Let’s remove the boiler plate code from above example and use try-with-resources feature of java 7.

    public void readFileWithTryWithResources(String fileName) 
    {
    	try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
    	{
    		String sCurrentLine;
    		while ((sCurrentLine = br.readLine()) != null) 
    		{
    			System.out.println(sCurrentLine);
    		}
    	} 
    	//Stream is closed automatically
    	catch (IOException e) 
    	{
    		e.printStackTrace();
    	} 	
    }
    
  3. Read file with java.nio.file.Files

    This is part of New Java IO API, and make the code easy to read.

    public void readFileWithNIO (String fileName) 
    {
    	Path path = Paths.get( fileName );
    	
        try ( Stream<String> lines = Files.lines(path) )
        {
            lines.forEach(s -> System.out.println(s));
        } 
        catch (IOException ex) {
        	ex.printStackTrace();
        }
    }
    
    Please notice the use of lines.forEachOrdered(). If you will use lines.forEach() then you may not get the lines in correct sequence due to asynchronous nature of API.
  4. Read file with Apache Commons IOUtils

    Apache commons IO library does an excellent job by providing short and easy to use methods for almost all of IO related jobs in java. .e. Reading a file using FileUtils is as easy as below example:

    public void readFileWithApacheCommons (String fileName) 
    {
        try 
        {
        	File file = new File( fileName );
        	List lines = FileUtils.readLines(file, "UTF-8");
        	for (String line : lines) {
    			System.out.println( line );
    		}
        } 
        catch (IOException ex) {
        	ex.printStackTrace();
        }
    }
    
  5. Read file with Guava

    Guava has similar approach as Apache commons. Only the class name is different – Use Files in place of FileUtils.

    public void readFileWithGuava (String fileName) 
    {
        try 
        {
        	File file = new File( fileName );
        	List lines = Files.readLines(file, "UTF-8");
        	for (String line : lines) {
    			System.out.println( line );
    		}
        } 
        catch (IOException ex) {
        	ex.printStackTrace();
        }
    }
    

Complete Example Sourcecode

package com.howtodoinjava.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadFileExamples 
{
	public static void main(String[] args) 
	{
		final String fileName = "Lorem Ipsum.txt";
		
		readFileWithNIO(fileName); //1  
		readFileWithTryWithResources(fileName); //2
		readFileWithNIO(fileName); //3
		readFileWithApacheCommons(fileName); //4
		readFileWithGuava(fileName); //5
	}
	
	public static void readFileWithBufferedReader(String fileName) 
	{
		BufferedReader br = null;
		try {
			String sCurrentLine;
			br = new BufferedReader ( new FileReader( fileName ) );
			while ((sCurrentLine = br.readLine()) != null) 
			{
				System.out.println(sCurrentLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				//Do not forget to close the stream
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
	
	public static void readFileWithTryWithResources(String fileName) 
	{
		try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
		{
			String sCurrentLine;
			while ((sCurrentLine = br.readLine()) != null) 
			{
				System.out.println(sCurrentLine);
			}
		} 
		//Stream is closed automatically
		catch (IOException e) 
		{
			e.printStackTrace();
		} 	
	}
	
	public static void readFileWithNIO (String fileName) 
	{
		Path path = Paths.get( fileName );
		
        try (Stream<String> lines = Files.lines(path))
        {
            lines.forEachOrdered(s -> System.out.println(s));
        } 
        catch (IOException ex) {
        	ex.printStackTrace();
        }
	}
	
	public static void readFileWithApacheCommons (String fileName) 
	{
        try 
        {
        	File file = new File( fileName );
        	List lines = FileUtils.readLines(file, "UTF-8");
        	for (String line : lines) {
				System.out.println("line:" + line);
			}
        } 
        catch (IOException ex) {
        	ex.printStackTrace();
        }
	}
	
	public static void readFileWithGuava (String fileName) 
	{
		try 
	    {
	    	File file = new File( fileName );
	    	List lines = Files.readLines(file, "UTF-8");
	    	for (String line : lines) {
				System.out.println( line );
			}
	    } 
	    catch (IOException ex) {
	    	ex.printStackTrace();
	    }
	}
	
}

Let me know if you think any other way to read a file in java – more efficient.

Happy Learning !!

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Feedback, Discussion and Comments

  1. Alejandro Daza

    May 23, 2016

    I think one important missing FileChannel

    Reply

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

Java IO Tutorials

  • IO – Introduction
  • IO – How it works?
  • IO – IO vs. NIO
  • IO – Copy Directory Recursively
  • IO – Delete Directory Recursively
  • IO – Create File
  • IO – Write to File
  • IO – Append to File
  • IO – Create Read Only File
  • IO – Read File to String
  • IO – Read File to Byte[]
  • IO – Read File Line by Line
  • IO – BufferedReader
  • IO – BufferedWriter
  • IO – Read/Write Properties File
  • IO – Read file from resources
  • IO – Read/Write UTF-8 Data
  • IO – Check if File Exist
  • IO – File Copy
  • IO – FilenameFilter
  • IO – FileFilter
  • IO – Create Temporary File
  • IO – Write Temporary File
  • IO – Delete Temporary File
  • IO – Read from Console
  • IO – Typesafe input using Scanner
  • IO – String to InputStream
  • IO – InputStream to String
  • IO – Password Protected Zip
  • IO – Unzip with Sub-directories
  • IO – Manage System Log Size
  • IO – Generate SHA / MD5

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap