Reading File using Java Program and Print Content to console

Reading File using Java Program

In this tutorial you will learn Simple example about Reading File Using Java Program and Print the content of file to console. The program has been tested and output is posted in the same article.

SimpleFileReading.java

package com.dineshkrish.example;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class SimpleFileReading {

	public static void main(String[] args) {
		
		String path = "D://data.txt"; // We can change path accordingly
		
		// Defining the File object with path of the file
		File file = new File(path);
		
		try {
			
			// Defining the Reader Object with File argument
			FileReader fileReader = new FileReader(file);
			
			int data = fileReader.read(); // Reading each character
			
			while(data != -1) { // Traverse up to no character to read( -1 if no character)
				
				// Printing the each character
				System.out.print((char)data); // Converting (ASCII Value) int to char
				data = fileReader.read();
			}
			
			fileReader.close();
			
		} catch (FileNotFoundException e) {
			
			System.out.println(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		
	}
	
}

File Content

The content which displayed in the below Image fie will be read by the above Java Program. using FileReader API and the same content will be displayed in the Console output.

Reading File using Java Program

Output

Reading File using Java Program

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.