Java File Handling
Java File Handling
Java has several methods for creating, reading, updating, and deleting files.
To use the File class, create an object of the class, and specify the filename or
directory name:
Example
import java.io.File; // Import the File class
If you don't know what a package is, read our Java Packages Tutorial.
The File class has many useful methods for creating and getting information
about files. For example:
You will learn how to create, write, read and delete files in the next chapters:
Create a File
To create a file in Java, you can use the createNewFile() method. This method
returns a boolean value: true if the file was successfully created, and false if the
file already exists. Note that the method is enclosed in a try...catch block. This
is necessary because it throws an IOException if an error occurs (if the file cannot
be created for some reason):
Example
import java.io.File; // Import the File class
try {
if (myObj.createNewFile()) {
} else {
} catch (IOException e) {
e.printStackTrace();
Run example »
Write To a File
In the following example, we use the FileWriter class together with
its write() method to write some text to the file we created in the example
above. Note that when you are done writing to the file, you should close it with
the close() method:
Example
import java.io.FileWriter; // Import the FileWriter class
try {
myWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Read a File
In the previous chapter, you learned how to create and write to a file.
Example
import java.io.File; // Import the File class
try {
while (myReader.hasNextLine()) {
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Example
import java.io.File; // Import the File class
if (myObj.exists()) {
} else {
Note: There are many available classes in the Java API that can be used to
read and write files in Java: FileReader, BufferedReader, Files, Scanner,
FileInputStream, FileWriter, BufferedWriter, FileOutputStream , etc. Which one to
use depends on the Java version you're working with and whether you need to
read bytes or characters, and the size of the file/lines etc.
Delete a File
To delete a file in Java, use the delete() method:
Example
import java.io.File; // Import the File class
public class DeleteFile {
if (myObj.delete()) {
} else {
Delete a Folder
You can also delete a folder. However, it must be empty:
Example
import java.io.File;
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {