Java Read Files
Reading Files in Java
Reading files is a fundamental operation in Java applications. Programs often need to retrieve stored data such as configuration settings, logs, or user-generated content.
In previous sections, you learned how to create and write data to files. Now, let's explore how to read data from a file using Java.
One of the simplest ways to read a text file in Java is by using the Scanner class together with the File class. The Scanner class allows you to read file content line by line or parse individual words and numbers.
If the specified file cannot be found, Java throws a FileNotFoundException, which must be handled using a try...catch block.
Example: Reading a Text File
The following Java program demonstrates how to read the contents of a file named data.txt and display it in the console.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReadExample {
public static void main(String[] args) {
File file = new File("data.txt");
try (Scanner reader = new Scanner(file)) {
System.out.println("File Contents:\n");
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException error) {
System.out.println("Unable to locate the specified file.");
error.printStackTrace();
}
}
}
Sample Output
File Contents:
Learning Java file handling.
Reading files using Scanner class.
Practice makes programming easier!
Program Explanation
- The program imports the File, FileNotFoundException, and Scanner classes.
- A File object is created to represent the file data.txt.
- The Scanner object reads the file content.
- The hasNextLine() method checks whether more lines are available.
- The nextLine() method reads each line from the file.
- The try-with-resources statement ensures the Scanner object is automatically closed
- after use.
Retrieving File Information in Java
Java also allows you to retrieve useful information about a file, such as its name, path, size, and access permissions.
The File class provides several methods for accessing file metadata.
Example: Display File Details
import java.io.File;
public class FileDetailsExample {
public static void main(String[] args) {
File file = new File("data.txt");
if (file.exists()) {
System.out.println("File Name: " + file.getName());
System.out.println("File Location: " + file.getAbsolutePath());
System.out.println("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
System.out.println("File Size (bytes): " + file.length());
} else {
System.out.println("File not found in the specified location.");
}
}
}
Sample Output
File Name: data.txt
File Location: C:\Projects\data.txt
Readable: true
Writable: true
File Size (bytes): 128