Java-File-Example
admin
File handling classes in Java
Updated: 13/Feb/2025 by Computer Hope
File handling is an essential module for learning effective programming. It allows developers to create, read, write, and manipulate files efficiently in Java. Mastering file handling is crucial for building robust Java applications, especially when dealing with large amounts of data stored in files.
File handling enables programmers to manage files and directories in the system programmatically. Java provides a built-in package called java.io
, which contains essential classes such as File
, FileReader
, FileWriter
, BufferedReader
, and BufferedWriter
to facilitate file operations.
Below are some essential methods that are frequently used in Java file handling:
File myFile = new File("D:/Assignments/Test Papers/Test Paper 1.docx");
myFile.exists()
myFile.getName()
myFile.isHidden()
Below is a Java program demonstrating how to check file existence, determine file type, and verify hidden status.
import java.io.*;
public class FileExample1 {
public static void main(String args[]) {
File myFile = new File("D:/Assignments/Test Papers/Test Paper 1.docx");
if (myFile.exists()) {
System.out.println(myFile.getName() + " is present");
} else {
System.out.println("File not present");
System.exit(0);
}
if (myFile.isFile()) {
System.out.println(myFile.getName() + " is a file");
} else {
System.out.println(myFile.getName() + " is a directory");
}
if (myFile.isHidden()) {
System.out.println(myFile.getName() + " is hidden");
} else {
System.out.println(myFile.getName() + " is not hidden");
}
}
}
File
class is used to reference a file stored in the system.exists()
method verifies if the specified file is present.isFile()
method determines whether the given path points to a file or a directory.isHidden()
method helps identify if a file is hidden.try {
FileReader reader = new FileReader("D:/Assignments/Test Papers/Test Paper 1.docx");
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, this is a file handling example in Java!");
writer.close();
System.out.println("File writing successful.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
try-catch-finally
) to handle file-related errors.
File handling in Java is an essential skill for every developer. Using the File
class and related methods, we can efficiently manage file operations such as reading, writing, and modifying files. Understanding these concepts will enable you to build better applications that interact with the file system efficiently.