File handling in Java allows us to create, read, write, update, and delete files stored on the system. In this chapter, we will learn what file handling is, why it is used, the concept of streams, common file methods, and different file operations with complete examples.
In Java, a file is a named location on disk used to store related information. File handling refers to the process of managing files programmatically, such as:
Java provides the java.io package to perform file handling operations.
A stream represents a sequence of data. File handling is performed using streams, which are classified into two types.
Byte Stream is used to handle byte-oriented data, such as images, audio files, and binary files.
Classes like FileInputStream and FileOutputStream are used for byte stream operations.
Character Stream is used to handle character-oriented data, such as text files.
Classes like FileReader, FileWriter, BufferedReader, and BufferedWriter are used for character stream operations.
The following are some commonly used methods of the File class:
| S.No. | Method | Return Type | Description |
|---|---|---|---|
| 1. | canRead() | Boolean | The canRead() method is used to check whether we can read the data of the file or not. |
| 2. | createNewFile() | Boolean | The createNewFile() method is used to create a new empty file. |
| 3. | canWrite() | Boolean | The canWrite() method is used to check whether we can write the data into the file or not. |
| 4. | exists() | Boolean | The exists() method is used to check whether the specified file is present or not. |
| 5. | delete() | Boolean | The delete() method is used to delete a file. |
| 6. | getName() | String | The getName() method is used to find the file name. |
| 7. | getAbsolutePath() | String | The getAbsolutePath() method is used to get the absolute pathname of the file. |
| 8. | length() | Long | The length() method is used to get the size of the file in bytes. |
| 9. | list() | String[] | The list() method is used to get an array of the files available in the directory. |
| 10. | mkdir() | Boolean | The mkdir() method is used for creating a new directory. |
The create a file operation is used to create a new file in the system. This operation is performed using the createNewFile() method of the File class. This method returns true if the file is created successfully and false if the file already exists at the specified location.
This example demonstrates how a new file is created using the createNewFile() method.
Output:


Explanation:
In the above code, we import the File and IOException class for performing file operation and handling errors, respectively. We create the f0 object of the File class and specify the location of the directory where we want to create a file. In the try block, we call the createNewFile() method through the f0 object to create a new file in the specified location. If the method returns false, it will jump to the else section. If there is any error, it gets handled in the catch block.
The get file Information operation is used to retrieve details about a file. Java provides several methods to obtain information such as the file name, absolute path, readability, writability, and file size (length).
This example demonstrates how to access and display different properties of a file, including its name, path, permissions, and size.
Output:

Description:
In the above code, we import the java.io.File package and create a class FileInfo. In the main method, we create an object of the text file which we have created in our previous example. We check the existence of the file using a conditional statement, and if it is present, we get the following information about that file:
If the file doesn't exist, we show a custom message.
The write to a file operation allows data to be stored inside a file. To write data, Java uses the FileWriter class along with its write() method. After writing data, it is important to close the stream using the close() method to release system resources.
This example demonstrates how data is written into a file using FileWriter and how closing the stream ensures that all data is saved properly.
Output:


Explanation:
In the above code, we import the java.io.FileWriter and java.io.IOException classes. We create a class WriteToFile, and in its main method, we use the try-catch block. In the try section, we create an instance of the FileWriter class, i.e., fwrite. We call the write method of the FileWriter class and pass the content to that function which we want to write. After that, we call the close() method of the FileWriter class to close the file stream. After writing the content and closing the stream, we print a custom message.
If we get any error in the try section, it jumps to the catch block. In the catch block, we handle the IOException and print a custom message.
The read from a file operation is used to read data stored in a file. Java commonly uses the Scanner class for this purpose. An instance of the Scanner class is created, and methods like hasNextLine() and nextLine() are used to read file content. After reading the data, the stream must be closed using the close() method.
This example demonstrates how file data is read line by line using the Scanner class.
Output:

Expalnation:
In the above code, we import the "java.util.Scannner", "java.io.File" and "java.io.IOException" classes. We create a class ReadFromFile, and in its main method, we use the try-catch block. In the try section, we create an instance of both the Scanner and the File classes. We pass the File class object to the Scanner class object and then iterate the scanner class object using the "While" loop and print each line of the file. We also need to close the scanner class object, so we use the close() function. If we get any error in the try section, it jumps to the catch block. In the catch block, we handle the IOException and print a custom message.
The delete a file operation is used to remove a file from the system. Java provides the delete() method of the File class to perform this task. Since no input or output stream is used while deleting a file, there is no need to close any stream.
This example demonstrates how an existing file is deleted using the delete() method and how Java confirms the deletion status.
Output:

Explanation:
In the above code, we import the File class and create a class DeleteFile. In the main() method of the class, we create f0 object of the file which we want to delete. In the if statement, we call the delete() method of the file using the f0 object. If the delete() method returns true, we print the success custom message. Otherwise, it jumps to the else section where we print the unsuccessful custom message.
All the above-mentioned operations are used to read, write, delete, and create file programmatically.
To check whether a file exists, the exists() method of the File class is used. This method checks the presence of a file or directory at the specified location and returns true if it is found; otherwise, it returns false.
This example demonstrates how Java checks the existence of a file before performing any file operation.
Output:
File exists
Java also allows creating directories (folders), which is useful when files need to be organized into specific locations. To create a directory, the mkdir() method of the File class is used that creates a single directory and returns true if the directory is created successfully or false if it already exists or cannot be created.
This example demonstrates how a new directory is created using Java file-handling methods.
Output:
Directory created successfully
You can list out all files and subdirectories present inside a directory by using the list() or listFiles() method of the File class. These methods retrieve the names or file objects of all entries available in the specified directory.
This example demonstrates how lists all files and folders available inside a directory.
Output:
file1.txt file2.txt subFolder
You can rename a file or move it to another location by using the renameTo() method of the File class. This method changes the name or path of the file and returns true if the operation is successful; otherwise, it returns false.
This example demonstrates how an existing file is renamed using Java file-handling functionality.
Output:
File renamed successfully
You can check and modify file permissions by using methods such as canRead(), canWrite(), canExecute(), setReadable(), setWritable(), and setExecutable() provided by the File class. You can also use the FilePermission class and its methods to read, write, and change the file's permissions.
This example demonstrates how Java checks and updates file access permissions.
Output:
true true
You can determine the size of a file and the last modified date by using the length() and lastModified() methods of the File class. These methods return the file size in bytes and the last modification time.
This example demonstrates how Java retrieves the file size and last modified timestamp.
Output:
1024 1707052800000
File operations may cause exceptions such as file not found or access denied. These situations are handled using Java's exception handling mechanism (try, catch, and finally).
This example demonstrates how Java handles exceptions that may occur during file operations.
Output:
File not found
We request you to subscribe our newsletter for upcoming updates.