w3resource

Java: Reading File

Introduction

Java has a concept of working with streams of data. You can say that a Java program reads sequences of bytes from an input stream (or writes into an output stream): byte after byte, character after character, primitive after primitive. Accordingly, Java defines various types of classes supporting streams, for example, InputStream or OutputStream. There are classes specifically meant for reading character streams such as Reader and Writer.

Before an application can use a data file, it must open the file. A Java application opens a file by creating an object and associating a stream of bytes with that object. Similarly, when you finish using a file, the program should close the file—that is, make it no longer available to your application.

Below is a list of very important java library classes related to Streams.

Class Description
InputStream Abstract class containing methods for performing input
OutputStream Abstract class containing methods for performing output
FileInputStream Child of InputStream that provides the capability to read from disk files
FileOutputStream Child of OutputStream that provides the capability to write to disk files
PrintStream Child of FilterOutputStream, which is a child of OutputStream; PrintStream handles output to a system’s standard (or default) output device, usually the monitor
BufferedInputStream Child of FilterInputStream, which is a child of InputStream; BufferedInputStream handles input from a system’s standard (or default) input device, usually the keyboard

READING FROM A FILE

We will write a java program to read from file and print file data on the user screen. Let’s understand way to associate a File object with the input stream:

  • You can pass the filename to the constructor of the FileInputStream class.
  • You can create a File object by passing the filename to the File constructor. Then, you can pass the File object to the constructor of the FileInputStream class.

The second method has some benefits: if you create a File object, you can use the File class methods, such as exists()and lastModified(), to retrieve file information. (Refer File Input Output Tutorial).

While working with stream classes we have to take care of checked exceptions, In our program, we are doing it using a try-catch block.

Java Code: 

package filepackage;
import java.io.*;
public class FileReadingDemo {
	public static void main(String[] args) {
		InputStream istream;
		OutputStream ostream;
		int c;
		final int EOF = -1;
		ostream = System.out;
		try {
			File inputFile = new File("Data.txt");
			istream = new FileInputStream(inputFile);
			try {
				while ((c = istream.read()) != EOF)
					ostream.write(c);
			} catch (IOException e) {
				System.out.println("Error: " + e.getMessage());
			} finally {
				try {
					istream.close();
					ostream.close();
				} catch (IOException e) {
					System.out.println("File did not close");
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
}

If File is missing from root directory, we will get following error.

directory structure image

After Creating file in project root directory, we will get file content as output.

File location

directory structure image

directory structure image

While the byte stream classes provide sufficient functionality to handle any type of I/O operation, they cannot work directly with Unicode characters. Since one of the main purposes of Java is to support the “write once, run anywhere” philosophy, it was necessary to include direct I/O support for characters. Now we will look at java program using character stream to read the file. This is very much similar to FileInputStream but JVM treats it differently. In below program, we are not handling the exception with try-catch block but we are adding throws clause in the method declaration. Output would be same as above program.

Java Code:  

package filepackage;
import java.io.*;
public class FileReadingCharacterStream {
	public static void main(String[] args) throws IOException{
		FileReader freader = new FileReader("Data.txt");
		BufferedReader br = new BufferedReader(freader);
		String s;
		while((s = br.readLine()) != null) {
		System.out.println(s);
		}
		freader.close();
	}
}

We can write same program using Java 7 syntax where we do not need to worry about closing of File and Stream resources. The output will be exactly same as above program.

Java Code: 

package filepackage;
import java.io.*;
public class FileReadingJava7Way {
	public static void main(String[] args) {
		File file = new File("Data.txt");
		try (FileInputStream fis = new FileInputStream(file)) {
 			int content;
			while ((content = fis.read()) != -1) {
				// convert to char and display it
				System.out.print((char) content);
			} 
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Summary

  • Java program reads sequences of bytes/characters using input streams.
  • File reading is step by step process which starts with creating file object (open the file), passing the file object to the input stream, reading stream data and processing, and finally, close the stream and file object.
  • We have discussed various ways to read the file as well as handle the exception.

Java Code Editor:

Previous: File Input and Output
Next: Writing file



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-tutorial/reading-the-file.php