Java File Handling

Java programming language provides functionality to handle files through code. Other than printing the results on the command line, programmer can also save results or read data from files. This is called File Handling.

For this purpose, Java programming language hasĀ java.io package. The File class in java.io package helps user to handle files. Java File Handling lets user to create, open, read, edit, close or delete a file. In order to perform these functions on a file, programmer has to introduce java.io.File class. The syntax is:

Once the File class is imported, programmer will create an object of the File class by using new keyword. The file name or directory name is written in double quotes (“”) inside the parenthesis (). The syntax is:

Here, objName is the name of object of File class and filename.txt is the name of file.

Java File Handling Methods

The table below shows the list of Java File handling methods and their descriptions provided by java.io.File class.

Sr.No.MethodDescription
1.boolean createNewFile()This method does not take any parameter. It creates an empty file and returns true if file is created successfully. Otherwise returns false.
2.boolean exits()This method checks whether the specified file exists or not and returns boolean value accordingly.
3.boolean canRead()This method checks whether the file given is readable or not. It returns true if file is readable otherwise returns false.
4.boolean canWrite()This method checks whether the given file is writeable or not. It returns true if writeable, otherwise returns false.
5.boolean delete()This method deletes the specified file and returns true if the file is deleted successfully. Otherwise returns false.
6.String getName()This method returns the name of specified file.
7.long length()This method returns the size of specified file in bytes.
8.String getAbsolutePath()This method returns the absolute path for the specified file.
9.boolean mkdir()This method creates a directory in the specified path. It returns true if the directory is created successfully, otherwise returns false.
10.boolean mkdirs()This method creates a directory and also creates all the parents of that directory.
11.String[] list()This method returns an array of file names present in the specified directory.
12.void close()This method closes the file.
Java File Handling Methods

Create a File

The createNewFile() method present in java.io.File class is used to create a file. Note that the method uses try catch block. The reason is that it throws an IOException if some error occurs and the file could not be created. The below example shows how to create a file using this method.

import java.io.File;  // Import File class
import java.io.IOException;  // Import IOException class to throw errors

public class FileCreation {  
  public static void main(String[] args) {  
    try {  
      File obj = new File("filename.txt");  
      if (obj.createNewFile()) {  
        System.out.println("File is created successfully: " + obj.getName());  // Returns the name of file
      } else {  
        System.out.println("File already exists.");  
      }  
    } catch (IOException e) {
      System.out.println("An error occurred while creating file.");  // Error message 
      e.printStackTrace();  
    }  
  }  
} 

The output of the above code after compilation is:

Programmer can also specify the directory to save the file in. for this purpose the path is added with file name while creating an object of File class. The syntax for creating file in a specific directory for Windows system is:

For windows, replace single backslash \ with double backslashes \\. For Linux and Mac use single forward slashes /. The syntax is:

Write to a File

Java File Handling allows programmer to write to a file by using its FileWriter class. The method write() writes text in the file. The below example shows how to write in a file. The best practice is to close the file after writing in it. The close() method is used to close the file.

import java.io.FileWriter;   // import the FileWriter class
import java.io.IOException;  // import the IOException class to handle exceptions

public class WriteInFile {  
  public static void main(String[] args) {  
    try {  
      FileWriter myFile = new FileWriter("filename.txt");
      myFile.write("Hello! Welcome to Tutorialsart website for Java Tutorials");
      myFile.close();
      System.out.println("Successfully written in the file.");
    } catch (IOException e) {
      System.out.println("An error occurred while writing in file.");
      e.printStackTrace();
    } 
  }  
} 

The output of the above code after compilation is:

Read from a File

The scanner class of Java allows the programmer to read from a file. The below example shows how to read contents from a file and then close the file:

import java.io.File;  // import the file class
import java.io.FileNotFoundException;  // import this class to handle errors
import java.util.Scanner; // import the Scanner class to read text files

public class ReadFile {
  public static void main(String[] args) {
    try {
      File obj = new File("filename.txt");
      Scanner fileReader = new Scanner(obj);
      while (fileReader.hasNextLine()) {
        String data = fileReader.nextLine();
        System.out.println(data);
      }
      fileReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred while reading from file.");
      e.printStackTrace();
    }
  }
}

The output of the above code after compilation is:

Delete a File

Programmer can also delete a file through Java File Handling. The delete() method in Java allows user to delete a file. Here is an example that deletes a file.

import java.io.File;  // import the File class

public class FileDeletion {
  public static void main(String[] args) { 
    File obj = new File("filename.txt"); 
    if (obj.delete()) { 
      System.out.println("The file: " + obj.getName() + " is deleted successfully.");
    } else {
      System.out.println("An error occurred in file deletion. Unable to delete the file.");
    } 
  } 
}

The output of the above code after compilation is: