English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/O)

Java Reader/Writer

Other Java topics

Java File Class

In this tutorial, we will learn about Java File and its various operations through examples.

The File class in the java.io package is used to perform various operations on files and directories.

There is also a java.nio package named, which can be used to handle files. However, in this tutorial, we will focus on the java.io package.

Files and directories

A file is a named location that can be used to store related information. For example,

main.javaIt is a Java file that contains information about Java programs.

A directory is a collection of files and subdirectories. Directories within a directory are called subdirectories.

Create a Java file object

To create the object File, we need to import the java.io.File package first. After importing the package, we can create a file object.

//Use the path to create a File object 
File file = new File(String pathName);

Here, we created a file object named file. This object can be used to handle files and directories.

NoteIn Java, creating a file object does not mean creating a file. Instead, a file object is an abstract representation of a file or directory path (specified in parentheses).

Java file operation methods

Operation methodMethodPackage
Create filecreateNewFile()java.io.File
Read fileread()java.io.FileReader
Write to filewrite()java.io.FileWriter
Delete filedelete()java.io.File

Java create file

To create a new file, we can use the createNewFile() method. It returns

  • true - If a new file has been created.

  • false - If the file already exists at the specified location.

Example: Create a new file

//Import File class
import java.io.File;
class Main {
  public static void main(String[] args) {
    //Create a file object for the current location
    File file = new File("newFile.txt");
    try {
      //Attempt to create a file based on this object
      boolean value = file.createNewFile();
      if (value) {
        System.out.println("A new file has been created.");
      }
      else {
        System.out.println("The file already exists.");
      }
    }
    catch(Exception e) {
      e.getStackTrace();
    }
  }
}

In the above example, we created a file object named file. This file object is linked to the specified file path.

File file = new File("newFile.txt");

Here, we used a file object to create a new file with a specified path.
If newFile.txt does not exist at the current location, then a file will be created and this message will be displayed.

A new file has been created.

But if newFile.txt already exists, we will see this message.

The file already exists.

Java read file

To read data from a file, we can useInputStreamOrReaderof subclasses.

Example: Reading a file using FileReader

Assuming we have a file namedinput.txtThe file contains the following content.

www.oldtoolbag.com    Java tutorial

Now, let's try to read a file using Java FileReader.

// Import FileReader
import java.io.FileReader;
class Main {
  public static void main(String[] args) {
    char[] array = new char[100];
    try {
      //Create a reader using FileReader
      FileReader input = new FileReader("input.txt");
      //Read characters
      input.read(array);
      System.out.println("文件中的数据:");
      System.out.println(array);
      // Close reader
      input.close();
    }
    catch(Exception e) {
      e.getStackTrace();
    }
  }
}

Output Result

Data in the file:
www.oldtoolbag.com    Java tutorial

In the above example, we use the FileReader to create an object named input. Now, it is already associated withinput.txtFile link.

FileReader input = new FileReader("input.txt");

To read frominput.txtRead data from the file, we used the FileReader's read() method.

Java write file

To write data to a file, we can useOutputStreamOrWriterof subclasses.

Example: Use FileWriter to write to a file

//Import FileWriter class
import java.io.FileWriter;
 class Main {
   public static void main(String args[]) {
     String data = "This is the data in the output file";
     try {
       //Create a Writer using FileWriter
       FileWriter output = new FileWriter("output.txt");
       //Write a string to the file
       output.write(data);
       System.out.println("Data has been written to the file.");
       //Close writer
       output.close();
     }
     catch(Exception e) {
       e.getStackTrace();
     }
  }
}

Output Result

Data is written to the file.

In the above example, we use the FileWriter class to create the writer .WriterWithoutput.txtFile link.

FileWriter output = new FileWriter("output.txt");

We use the write() method to write data to the file.

Here, when we run the program,output.txtThe file will be filled with the following content.

www.oldtoolbag.com    Java tutorial

Java delete file

We can use the delete() method of the File class to delete the specified file or directory. It returns

  • true   - If the file has been deleted.

  • false  - If the file does not exist.

NoteWe can only delete empty directories.

Example: Delete a file

import java.io.File;
class Main {
  public static void main(String[] args) {
    //Create a file object
    File file = new File("file.txt");
    //Delete the file
    boolean value = file.delete();
    if(value) {
      System.out.println("The file has been deleted.");
    }
    else {
      System.out.println("The file has been deleted.");
    }
  }
}

Output Result

The file has been deleted.

In the above example, we created a File object named File. The file now contains information about the specified file.

File file = new File("file.txt");

Here, we used the delete() method to delete the file specified by the object.