Monday, April 28, 2025

Java OO Tutorial - Reading a Text File in Java

Our Java program import needed classes from the java.io package: File and FileNotFoundException.

The File class is used to represent a file or directory in the file system. It provides methods to create, read, update, and delete files and directories.

The FileNotFoundException class is a type of IOException that is thrown when a file cannot be found during file I/O operations. It is often used in conjunction with the File class to handle errors that may occur when working with files.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {	
	
	public static void main(String[] args) {

		try {
			File fileObj = new File("externalfile.txt");
			Scanner readFile = new Scanner(fileObj);
			
			while (readFile.hasNextLine()) {
				System.out.println(readFile.nextLine());
			}
			
			readFile.close(); 
			} 
		catch (FileNotFoundException e) {
				System.out.println("This file doesn't exists ");
				System.out.println(e);
			} 
		finally {
				System.out.println("---------------------------");
				System.out.println("I will work no matter what.");
				System.out.println("---------------------------");
			}		
	}		
}

Here's an explanation of the code block by block: 

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {	
	
	public static void main(String[] args) {

The program starts with the standard header for a Java file, which includes the package and import statements. In this case, we're importing java.io.File, java.io.FileNotFoundException, and java.util.Scanner

try {
	File fileObj = new File("externalfile.txt");
	Scanner readFile = new Scanner(fileObj);

The code then creates a File object called fileObj that represents the file we want to read. The filename is "externalfile.txt".

A Scanner object is then created with the File object as an argument. This sets up a scanner to read from the specified file. 

while (readFile.hasNextLine()) {
	System.out.println(readFile.nextLine());
}

The while loop reads each line of the file until there are no more lines to read. The hasNextLine() method checks whether there is another line in the file, and nextLine() reads the next line. 

readFile.close();

Once the file has been read, the Scanner object is closed using the close() method. This is good practice to ensure that system resources are freed up. 

It is important to close files while operating on them with programming languages for several reasons:

  1. Release of resources: When a file is opened, the operating system allocates resources to it, such as memory and CPU time. Closing the file releases these resources, freeing them up for other programs or processes to use.

  2. Data integrity: If data is still being written to a file when it is closed, it can become corrupted or incomplete. Closing the file ensures that all data has been written to it and that it is saved in a consistent state.

  3. Security: Open files can be accessed by other programs or processes, potentially leading to data breaches or other security issues. Closing the file ensures that it is no longer accessible to other programs.

In most programming languages, failing to close a file can result in resource leaks or other errors that can impact performance, stability, or security. Therefore, it is generally good practice to close files as soon as they are no longer needed.

} catch (FileNotFoundException e) {
	System.out.println("This file doesn't exists ");
	System.out.println(e);
}

If the file specified in the File object is not found, a FileNotFoundException will be thrown. The catch block catches the exception and prints a message to the console. 

finally {
	System.out.println("---------------------------");
	System.out.println("I will work no matter what.");
	System.out.println("---------------------------");
}

The finally block is executed after the try block has finished executing, regardless of whether an exception was thrown or not. This block simply prints a message to the console to indicate that it has been executed.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...