JavaJava File Class

Java File Class

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Java Programming tutorials

Located in the java.io package, the Java File class is Java’s representation of a file or directory pathname. It contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the contents of a directory, and determining common attributes of files and directories. This tutorial will cover other aspects of the File class including how to instantiate one, the different path types, getting information about a file, listing files, and working with files.

How to Create a File Object in Java

In a tutorial I wrote for TechRepublic (Directory Navigation in Java), we passed an absolute file path to the constructor, as shown in the following code example:

File file = new File("C:\\My Documents");

The code above creates an abstract representation of the Windows “My Documents” folder – also referred to as an abstract pathname.

Developers can also refer to a file as follows:

// Using a relative path
File linuxFile   = new File("/Java/myfile.csv");
// Using an absolute path
File windowsFile = new File("F:\\Java\\myfile.txt");

The File class has a few other constructors that we did not use. Here is a description of those:

  • File(File parent, String child): Creates a new File instance from a parent File and a child pathname string.
  • File(String parent, String child): Creates a new File instance from a parent pathname string and a child pathname string.
  • File(URI uri): Creates a new File instance by converting the given file URI into an abstract pathname.

Read: Java Thread Class

Java Relative Pathnames

As denoted by the name, a relative pathname is interpreted through information taken from some other pathname. This information is obtained from the current directory of your program. The relative pathname is then combined with the current directory path in order to find the requested file. If you are ever unsure what the current directory is, you can find out by calling the System.getProperty() method:

System.getProperty("user.dir");

How to Get Information about  a Java File Object

Once a programmer has instantiated a new File object, they can obtain a lot of information about it. Here is a list of methods that can help with that:

  • public String getName(): Returns the name of the file or directory denoted by this abstract pathname.
  • public String getParent(): Returns the pathname string of this abstract pathname’s parent, or null if this pathname does not name a parent directory.
  • public File getParentFile(): Returns the abstract pathname of this abstract pathname’s parent, or null if this pathname does not name a parent directory.
  • public String getPath(): Converts this abstract pathname into a pathname string.
  • public boolean isAbsolute(): Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise.
  • public String getAbsolutePath(): Returns the absolute pathname string of this abstract pathname.
  • public String getCanonicalPath(): Returns the Canonical pathname of this abstract pathname. If the pathname of the file object is Canonical then it simply returns the path of the current file object. The Canonical path is always absolute and unique, the function removes the ‘.‘ and ‘..‘ from the path, if present.
  • public boolean canRead(): Tests whether the application can read the file denoted by this abstract pathname. Returns true if and only if the file specified by this abstract pathname exists and can be read by the application, or false otherwise.
  • public boolean canWrite(): Tests whether the application can modify to the file denoted by this abstract pathname. Returns true if – and only if – the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
  • public boolean exists(): Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this abstract pathname exists, or false otherwise.
  • public boolean isDirectory(): Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a directory, or false otherwise.
  • public boolean isFile(): Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file. Returns true if – and only if – the file denoted by this abstract pathname exists and is a normal file, or false otherwise.
  • public long lastModified(): Returns the time that the file denoted by this abstract pathname was last modified. Returns a long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.
  • public long length(): Returns the length of the file denoted by this abstract pathname, in bytes. The return value is unspecified if this pathname denotes a directory.
  • public String toString(): Returns the pathname string of this abstract pathname. This is the same string returned by the getPath() method.

This modified version of the first program displays a number of File properties:

package com.developer;

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

public class GetFileInfoExample {
  public static void main(String[] args) throws IOException {
    // Store the name of files and directories
    // in an array of Files.
    // Don't forget to escape the backslash character!
    File[] files = new File("C:\\My Documents").listFiles();
    
    // Traverse through the files array
    for (File file : files) {
      // If a subdirectory is found,
      // print the name of the subdirectory
      System.out.println("Is a Directory? " + file.isDirectory());	
      System.out.println("Is a File? " + file.isFile());
      if (file.isDirectory()) {
        System.out.println("Directory: " + file.getName());
      }
      else {
        // Print the file name
        System.out.println("File: " + file.getName());
      }
      System.out.println("Exists? " + file.exists());
      System.out.println("Parent: " + file.getParent());
      System.out.println("Path: " + file.getPath());
      System.out.println("Is absolute? " + file.isAbsolute());
      System.out.println("Absolute path: " + file.getAbsolutePath());
      System.out.println("Caninocal path: " + file.getCanonicalPath());
      System.out.println("Is readable? " + file.canRead());
      System.out.println("Is writable? " + file.canWrite());
      System.out.println("Is executable? " + file.canExecute());
      System.out.println("Last modified: " + file.lastModified());
      System.out.println("Length (in bytes): " + file.length());  
    }
  }
}

Here are the properties of the first couple of Files:

//File 1:
Is a Directory? true
Is a File? false
Directory: AAMS
Exists? true
Parent: I:\My Documents
Path: I:\My Documents\AAMS
Is absolute? true
Absolute path: I:\My Documents\AAMS
Caninocal path: I:\My Documents\AAMS
Is readable? true
Is writable? true
Is executable? true
Last modified: 1588454396994
Length (in bytes): 0
Is a Directory? true
Is a File? false
Directory: Addictive Drums
Exists? true
Parent: I:\My Documents
Path: I:\My Documents\Addictive Drums
Is absolute? true
Absolute path: I:\My Documents\Addictive Drums
Caninocal path: I:\My Documents\Addictive Drums
Is readable? true
Is writable? true
Is executable? true
Last modified: 1075183575015
Length (in bytes): 0
//File 2:
Is a Directory? true
Is a File? false
Directory: Angular
Exists? true
Parent: I:\My Documents
Path: I:\My Documents\Angular
Is absolute? true
Absolute path: I:\My Documents\Angular
Caninocal path: I:\My Documents\Angular
Is readable? true
Is writable? true
Is executable? true
Last modified: 1535211679142
Length (in bytes): 0
Is a Directory? true
Is a File? false
Directory: angular-starter
Exists? true
Parent: I:\My Documents
Path: I:\My Documents\angular-starter
Is absolute? true
Absolute path: I:\My Documents\angular-starter
Caninocal path: I:\My Documents\angular-starter
Is readable? true
Is writable? true
Is executable? true
Last modified: 1539441641426
Length (in bytes): 0

Read: IntelliJ IDEA Review

Listing Files in Java

Of course, we have already seen listFiles() in action in both of the above examples. For completeness, here are all of the File methods that return a list of files or pathnames:

  • public String[] list(): Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
  • public String[] list(FilenameFilter filter): Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
  • public File[] listFiles(): Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
  • public File[] listFiles(FileFilter filter): Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

How to Work with Files in Java

The Java File class also contains a number of methods for creating a physical file or directory, as well as for modifying and deleting them. They are listed below:

  • public boolean createNewFile() throws IOException: Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. Returns true if the named file does not exist and was successfully created; false if the named file already exists.
  • public boolean delete(): Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Returns true if and only if the file or directory is successfully deleted, or false otherwise.
  • public void deleteOnExit(): Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
  • public boolean mkdir(): Creates the directory named by this abstract pathname. Returns true if and only if the directory was created, or false otherwise.
  • public boolean mkdirs(): Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Returns true if and only if the directory was created, along with all necessary parent directories, or false otherwise.
  • public boolean renameTo(File dest): Renames the file denoted by this abstract pathname. Returns true if and only if the renaming succeeded, or false otherwise.
  • public boolean setLastModified(long time): Sets the last-modified time of the file or directory named by this abstract pathname. Returns true if and only if the operation succeeded, or false otherwise.
  • public boolean setReadOnly(): Marks the file or directory named by this abstract pathname so that only read operations are allowed. Returns true if and only if the operation succeeded, or false otherwise.
  • public static File createTempFile(String prefix, String suffix, File directory) throws IOException: Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. Returns an abstract pathname denoting a newly-created empty file.
  • public static File createTempFile(String prefix, String suffix) throws IOException: Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. Invoking this method is equivalent to invoking createTempFile(prefix, suffix, null). Returns abstract pathname denoting a newly-created empty file.
  • public int compareTo(File pathname): Compares two abstract pathnames lexicographically. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically (i.e. by dictionary order) less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.
  • public int compareTo(Object o): Compares this abstract pathname to another object. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.
  • public boolean equals(Object obj): Tests this abstract pathname for equality with the given object. Returns true if – and only if – the argument is not null and is an abstract pathname that denotes the same file or directory as this abstract pathname.

Let’s give a few of these methods a try. Here is an example program that creates a file in the current working directory, renames it, and then attempts to delete both the original and renamed file from the drive:

package com.developer;

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

public class FileOperationsExample {
  public static void main(String args[]) {  
    try {  
      // Creating an object of a file  
      File testFile = new File("FileOperationsExample.txt");   
      if (testFile.createNewFile()) {  
        System.out.println("File " + testFile.getName() + " is created successfully.");  
        System.out.println("Path is " + testFile.getAbsolutePath());  
      } else {  
        System.out.println("File is already exist in the directory.");  
      }  
      File renamedTestFile = new File("FileOperationsExampleRenamed.txt");
      boolean renamed = testFile.renameTo(renamedTestFile);
      if (renamed) {
        System.out.println("File has been renamed to " + testFile.getName());  
      } else {
        System.out.println("Could not rename the File.");
      }
      
      boolean isDeleted = renamedTestFile.delete();
      if (isDeleted) {
        System.out.println("The renamed test file has been successfully deleted.");
      } else {
        System.out.println("Could not delete the renamed test file.");
      }
      
      // This will fail because the testFile has been renamed
      isDeleted = testFile.delete();
      if (isDeleted) {
        System.out.println("The test file has been successfully deleted.");
      } else {
        System.out.println("Could not delete the test file.");
      }
    } catch (IOException exception) {  
      System.out.println("An unexpected error is occurred.");  
      exception.printStackTrace();  
    }   
  }  
}

Although we could delete the renamed file, the delete() failed on the original file since it no longer exists!

File FileOperationsExample.txt is created successfully.
Path is I:\article-workspace\directoryNavigation\FileOperationsExample.txt
File has been renamed to FileOperationsExample.txt
The renamed test file has been successfully deleted.
Could not delete the test file.

Final Thoughts on the Java File Class

In this programming tutorial, we learned how to instantiate a File, about the different path types, how to get information about a File, list Files, and working with Files. You my have noticed that the File class does not contain any methods for reading or writing to a file. Those are part of several other classes that are organized by file type, i.e. text versus binary, and how they read and/or write to it, i.e. one line at a time, using a buffer, or all at once.

Read: Top Java Frameworks

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories