SSJX.CO.UK
Content

Java Reading a Text File

In Java, there are dozens of ways to read a text file. The following is one of the simplest ways to read a text file line by line.

Does the file exist?

A missing or moved file is not an exceptional event, first we check our file actually exists:

	File myfile = new File("myfile.txt");

	if (myfile.isFile()){
		// If we are here, then our file exists!
	}else{
		System.out.println("The file does not exist or is not a file!");
	}

The reason we use 'isFile()' instead of 'exists()' is that if myfile was given a directory / folder that exists, it would pass the check. We are only interested in actual files.

Reading a text file line by line

The following uses a 'try with resources' block to handle opening our file. This try block also takes care of closing our file and catches any exceptions that could occur. In this instance, an exceptional event could be the file going offline mid read. The while loop reads each line of our file and exits when there are no more lines in the file.

try(var fr=new FileReader(myfile); var in = new BufferedReader(fr)) {
		
	String line;
	while((line = in.readLine()) != null){
		System.out.println(line);
	}
	
}catch(IOException e){
	System.out.println("There was a problem opening this file!");
	System.out.println(e);
}

Full Java Program

With the Java JDK installed, from a command line:

If you do not have Java JDK installed, click the following link to find out how to install Java on your computer!

import java.io.*;

class Readfile{
	public static void main(String[] arguments){
		File myfile = new File("myfile.txt");

		if (myfile.isFile()){
			try(var fr=new FileReader(myfile); var in = new BufferedReader(fr)) {	
				String line;
				while((line = in.readLine()) != null){
					System.out.println(line);
				}
			}catch(IOException e){
				System.out.println("There was a problem opening this file!");
				System.out.println(e);
			}
		}else{
			System.out.println("The file does not exist or is not a file?");
		}
	}	
}

Updated (28/06/2026)