In many cases, the program needs to access certain files in its work. For example, user data can be recorded in some external file, and in order to read it, the program needs to be able to work with it — open, read data, possibly edit and close. For these purposes, the Java programming language has the Java.io.File Class. In this article, we will consider what kind of class it is and give an example of working with it.

What is Java File class

The File class is defined in the java.io package and it doesn’t work directly with streams. Java File class is to manage information about files and directories. As you know, at the operating system level, files and directories are different objects. However in Java, they both are described by the same File class. You might be wondering why not just use strings to refer to files? First of all, because file access is different in different operating systems.

File class constructors

Depending on whether the Java.io.File Class object should represent a file or a directory, we can use one of the constructors to create the object: File(String pathname) in this case constructor creates a new File instance by converting the given pathname string into an abstract pathname. File(String myPath, String myString) this constructor creates a new File instance from a myPath pathname string and a myString pathname string. File(File parent, String name) creates a new File instance from a file abstract pathname and a name pathname string. File(URI uri) in this case constructor creates a new File instance by converting the given file: URI into an abstract pathname. URI is a Java class that represents a Uniform Resource Identifier (URI) reference. Here is an example of different Java.io.File Class constructors:

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

public class FileTest {
   public static void main(String[] args) throws URISyntaxException {
       File myFile1 = new File("d:\\MyCat");
       File myFile2 = new File ("d:\\MyCat", "cat.txt");
       File myFile3 = new File(myFile1, "cat.txt");
       URI uri = new URI ("https://docs.oracle.com/javase/7/docs/api/java/net/URI.html");
       File myFile4 = new File(uri);
   }
}

Methods of File Class

Java File class has a number of methods that allow you to manipulate files and directories. Let's consider some of them:
  • boolean createNewFile() creates a new file at the path passed to the constructor. Returns true if successful, otherwise false

  • boolean delete() deletes a directory or file in the path passed to the constructor. Returns true on successful deletion

  • boolean exists() checks if a file or directory exists at the path specified in the constructor. If the file or directory exists, returns true, else returns false

  • String getAbsolutePath() returns the absolute path for the path passed to the object's constructor

  • String getName() returns the short name of a file or directory

  • String getParent() returns the name of the parent directory

  • boolean isDirectory() returns true if the given path contains a directory

  • boolean isFile() returns true if there is a file at the given path

  • boolean isHidden() returns true if the directory or file is hidden

  • long length() returns the size of the file in bytes

  • long lastModified() returns the time when a file or directory was last modified. The value represents the number of milliseconds that have passed since the Unix epoch

  • String[] list() returns an array of files and subdirectories that are in a specific directory

  • File[] listFiles() returns an array of files and subdirectories that are in a specific directory

  • boolean mkdir() creates a new directory and returns true if successful

  • boolean renameTo(File dest) renames a file or directory

Some features of Java File class

  • The path, abstract or string, can be either absolute or relative. The parent of an abstract path can be retrieved by calling the getParent() method of that class.

  • First we should create an object of the File class, passing it the name of a file or directory. The file system can impose restrictions on certain operations on the actual file system object, such as reading, writing, and executing. These restrictions are called access permissions.

  • Instances of the File class are immutable. That means, that once you create a file, the abstract path represented by the File object will never change.

Java.io.File Class - 1

File class code examples

Let’s create a program that works with directories. First of all it should create a directory at the given path and then create a new file and check if the file and directory exist.

import java.io.File;
import java.io.IOException;

public class FileTest2 {
   public static void main(String[] args) throws IOException {

       //create a directory using mkdir() File class method
       File dir = new File("d:\\MyDir");
       boolean created = dir.mkdir();
       if(created)
           System.out.println("Folder has been created...");
       else
           System.out.println("Folder hasn't been created...");
       File myFile = new File("d:\\MyDir\\cat.txt");
       myFile.createNewFile();
       System.out.println("File name: " + myFile.getName());
       System.out.println("Parent folder: " + myFile.getParent());
       if(myFile.exists())
           System.out.println("File exists");
       else
           System.out.println("File not found");
      }
}
Here is the output:
Folder has been created... File name: cat.txt Parent folder: d:\MyDir File exists
By the way if you did everything right, you can find a new directory and file at your computer. Now let’s write a program where we can work with the directory created and the file. Here we use some of the methods that are described above.

import java.io.File;

public class FileTest3 {

   public static void main(String[] args) {

       File dir = new File("d:\\MyDir");
       File myFile = new File("d:\\MyDir\\cat.txt");
       System.out.println("File name: " + myFile.getName());
       System.out.println("Parent folder: " + myFile.getParent());
       if (myFile.exists())
           System.out.println("File exists");
       else
           System.out.println("File not found");

       System.out.println("Absolute path: " + myFile.getAbsolutePath());

       if (myFile.exists()) {
           System.out.println("Is writable: " + myFile.canWrite());
           System.out.println("Is readable: " + myFile.canRead());
           System.out.println("Is a directory: " + myFile.isDirectory());
           System.out.println("myFile Size in bytes = " + myFile.length());

       }
   }
}
The output of the program is:
File name: cat.txt Parent folder: d:\MyDir File exists Absolute path: d:\MyDir\cat.txt Is writable: true Is readable: true Is a directory: false myFile Size in bytes = 0