How to read a file in Java

286 Flares Twitter 0 Facebook 0 Google+ 286 LinkedIn 0 Filament.io 286 Flares ×

In Java, you can adopt many ways to read contents of a file. In this tutorial let us explore the most common way of reading a file using java. The steps for reading a file can be broadly broken down into 3 simple steps

  1. Open a reader
  2. Wrap the reader in a buffered reader
  3. Read the lines until there is nothing more to read

[source language=”java”]package com.javahash.sample;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

/**
* @param args
*/
public static void main(String[] args) {
BufferedReader br = null;
try {

String currentLine;
br = new BufferedReader(new FileReader("E:\hello.txt"));
StringBuffer fileContents=new StringBuffer();

while ((currentLine = br.readLine()) != null) {
fileContents.append(currentLine);
fileContents.append("rn");
}
System.out.println(fileContents.toString());

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

}

}

Above code is very simple to understand. The code first creates a FileReader instance, by supplying the file name as the constructor argument. Next it wraps the reader in a BufferedReader. Why did we use BufferedReader and why just the reader alone ? The answer is – “to improve the performance and scalability”. Buffering can speed up IO quite a bit. Instead of reading one character at a time from the disk, you read a larger block at a time. This is typically much faster, especially for larger data amounts.

Java 7 has introduced the concept of try-with-resources. The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. This means with java 7 you no longer need to explicitly close the file if  you use the try-with-resource option.

The earlier code is simplified as below ( Java 7 or later only)

[source language=”java”]try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}

Here we have defined the BufferedReader inside the try-with-resources statement (The parentheses immediately following the try keyword). This will ensure that the JVM will close the BufferedReader regardless of whether the program ends successfully or ends in an Exception. There is no need for the finally block to close the resource explicitly. Please note that for the auto close to work the resource must implement the interface java.lang.AutoCloseable.  In Java 7 and upwards, BufferedReader class implements AutoCloseable and that’s why it works.