-
Hajipur, Bihar, 844101
Working with files is an important part of most Java programs. Whether you want to save user data, read configuration files, or store logs, Java provides built-in classes and methods to handle file operations easily. The java.io and java.nio.file packages contain everything you need to create, read, write, and delete files.
In this tutorial, you’ll learn what file handling in Java means, how the file system works, and which classes and methods are commonly used to manage files.
File handling is the process of performing operations like creating, reading, writing, or deleting files using Java code. Instead of manually dealing with files, Java gives you a set of classes that simplify these tasks.
Files can store data permanently, unlike variables that lose their values once the program stops. So, when you want your program to remember data for future use, you use file handling.
Some of the main file operations in Java include:
Creating a new file
Writing data into a file
Reading data from a file
Deleting or renaming a file
Checking file details like name, size, or path
There are two main packages used for file handling:
java.io package – This package provides the older, traditional approach to handling files using classes like File, FileReader, and FileWriter.
java.nio.file package – This package is part of the New I/O (NIO) system introduced in Java 7. It offers a more modern and efficient way to handle files using classes like Files, Paths, and Path.
Both are widely used, but the java.nio.file package is preferred for new projects because it supports better performance, error handling, and modern features.
The most commonly used class for file handling in the java.io package is the File class. It represents a file or a directory in the system. However, the File class doesn’t actually read or write the file content—it only provides information and control over the file itself.
You can create a File object using its constructor:
import java.io.File;
public class FileExample {
public static void main(String[] args) {
File file = new File("example.txt");
System.out.println("File object created successfully.");
}
}
Here, "example.txt" is the name of the file. This doesn’t create the file physically on your system yet—it just represents a path.
Before creating or using a file, it’s often useful to check if it already exists. You can use the exists() method for that.
if (file.exists()) {
System.out.println("File already exists.");
} else {
System.out.println("File does not exist.");
}
This helps prevent overwriting or duplication issues.
To actually create a file on your system, use the createNewFile() method. This method returns true if the file was created successfully and false if it already exists.
import java.io.File;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
try {
File myFile = new File("data.txt");
if (myFile.createNewFile()) {
System.out.println("File created: " + myFile.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The File class allows you to access file details such as its name, path, size, and permissions. Here’s an example:
import java.io.File;
public class FileInfo {
public static void main(String[] args) {
File myFile = new File("data.txt");
if (myFile.exists()) {
System.out.println("File name: " + myFile.getName());
System.out.println("Absolute path: " + myFile.getAbsolutePath());
System.out.println("Writable: " + myFile.canWrite());
System.out.println("Readable: " + myFile.canRead());
System.out.println("File size: " + myFile.length() + " bytes");
} else {
System.out.println("File does not exist.");
}
}
}
These methods are useful when you want to verify the file’s attributes before performing operations on it.
The same File class can also be used to handle directories (folders). You can create a directory using the mkdir() method.
import java.io.File;
public class CreateDirectory {
public static void main(String[] args) {
File folder = new File("MyFolder");
if (folder.mkdir()) {
System.out.println("Directory created successfully.");
} else {
System.out.println("Directory already exists or cannot be created.");
}
}
}
To create multiple nested folders, use mkdirs() instead of mkdir().
If you prefer a modern approach, the java.nio.file package gives you better tools for file management. You can use the Files and Paths classes to perform operations more easily.
Example of checking if a file exists using Files:
import java.nio.file.*;
public class NioExample {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
if (Files.exists(path)) {
System.out.println("File exists.");
} else {
System.out.println("File not found.");
}
}
}
You can also copy, move, and delete files using methods like Files.copy(), Files.move(), and Files.delete().
| Method | Description |
|---|---|
createNewFile() |
Creates a new empty file |
exists() |
Checks if the file or directory exists |
delete() |
Deletes a file or directory |
mkdir() |
Creates a directory |
canRead() / canWrite() |
Checks read/write permissions |
length() |
Returns file size in bytes |
list() |
Lists files inside a directory |
Here are some useful tips to keep in mind:
Always handle exceptions: File operations can fail due to missing permissions, incorrect paths, or locked files. Always use try-catch blocks.
Close resources properly: When reading or writing files, make sure to close file streams to avoid memory leaks.
Use absolute paths carefully: Relative paths are safer for portability across systems.
Avoid hardcoding file names: Use variables or configuration files for file paths.
Check file permissions: Always ensure the file can be read or written before performing operations.
File handling in Java is a core concept that allows programs to interact with the file system. The File class and Files utility methods make it easy to manage files and directories, whether you need to create, check, or delete them.
In upcoming chapters, you’ll learn how to perform specific file operations such as:
Creating and writing to files
Reading files
Deleting files
Each of these topics builds on the concepts covered here.
Write a Java program to create a new file named notes.txt and print whether it was created successfully or already exists.
Write a program to check if a file named report.txt exists in the current directory. If it exists, print its absolute path.
Create a Java program that prints all the details of a file such as its name, size, read/write permissions, and absolute path.
Write a program to create a new directory named MyDocuments. If it already exists, display a message saying so.
Write a Java program that creates multiple nested folders like Parent/Child/SubChild using the mkdirs() method.
Using the java.nio.file package, write a program to check if a file named data.txt exists. If not, create it.
Write a Java program that lists all files and folders inside a directory named MyFolder.
Write a Java program to check whether a given file is readable and writable.
Write a program that deletes a file named temp.txt if it exists. Display an appropriate message if it doesn’t.
Write a program using the Files and Paths classes to print “File found” if the file example.txt exists, otherwise print “File not found.”