File Class in Java

The File class in Java is used to represent the files and directories paths but not the data of the file. Basically, this class is used to create, delete, and rename the files and directories. It is also used to know the information about the files and directories like the given name represents file or directories, last-modified time, is file read-only, is file writable, display all directory and files in a given folder and etc.

Instances of the File class are immutable; i.e. once created, the abstract pathname represented by a File object will never change, because we do not have a setter method to change the file name in this File object. But we have a getter method to get the file name.

The File class implements Serializable, Comparable interfaces and it is available since JDK1.0 version on wards.

In Unix, everything is treated as a file. Java File concept is implemented based on the Unix operating system, hence file objects can be used to represent both files and directories. In Windows operating system, the directories are also called folders. In this topic whenever a “File” word is used, it represents both file and directory.

Java File Class constructor

The file class has below constructors to create its object.

  • public File(String pathname)
  • public File(String parent, String child)
  • public File(File parent, String child)
  • public File(URI uri)

Note:- File class object creation doesn’t not create any physical files, it only creates instance of the File class.

public File(String pathname)
Used to creates a new File instance with the given file name. Example:- The “xyz.txt” file is used from the current working directory.
File f = new File("xyz.txt");

public File(String parent, String child)
It creates a new File instance with the given parent file and child path. Example:- The “xyz.txt” file is used from the “workspace” folder from the current working directory.
File f = new File("workspace", "xyz.txt");

public File(File parent, String child)
It creates a new File instance with the given parent file and child path. To use this constructor parent file name must be passed as File class object. Example:- The “xyz.txt” file is used from the “workspace” folder from the current working directory.
File f1 = new File("workspace");
File f2 = new File(f1, "xyz.txt");

public File(URI uri)
It creates a new File instance by converting the given file: URI into the abstract pathname. Example:-
File f1 = new File("xyz.txt");
File f2 = new File(f1.toURI());

Important points while using these constructors

1) If we pass null as parent or file then it gives an ambiguous error because it is matched with the multiple constructors.
File f1 = new File(null); // ambigous error
File f2 = new File(null, "xyz.txt"); //ambigous error

2) If we pass null as the child argument then it doesn’t give a compile-time error but it throws NullPointerException.
File f3 = new File("workspace", null); // NullPointerException
File f = new File("pqr");
File f4 = new File(f,null); // NullPointerException

Program to create File class objects & display them

When a File class object is created, JVM just creates a File class object with the given name as that object state. It won’t check for the file or directory with the given name exist or not.

import java.io.File;
public class FileConstructorsTest {
   public static void main(String[] args) {

      File f1 = new File("xyz.txt");
      System.out.println("f1: "+f1);
      File f2 = new File("pqr"); 
      System.out.println("f2: "+f2);

      File f3 = new File("workspace", "abc.txt");
      System.out.println("f3: "+f3);

      File f4 = new File(f2,"abc.txt");
      System.out.println("f4: "+f4);

      File f5 = new File(f1.toURI());
      System.out.println("f5: "+f5);
      File f6 = new File(f2.toURI());
      System.out.println("f6: "+f6);
      File f7 = new File(f3.toURI());
      System.out.println("f7: "+f7);
      File f8 = new File(f4.toURI());
      System.out.println("f8: "+f8);

      File f9 = new File(f5.toURI());
      System.out.println("f9: "+f9);
   }
}

Output in Linux operating system, where current working directory is “/home/user/java“:-

f1: xyz.txt
f2: pqr
f3: workspace/abc.txt
f4: pqr/abc.txt
f5: /home/user/java/xyz.txt
f6: /home/user/java/pqr
f7: /home/user/java/workspace/abc.txt
f8: /home/user/java/pqr/abc.txt
f9: /home/user/java/xyz.txt

Output in Windows operating system, where current working directory is “D:\java\”:-

f1: xyz.txt
f2: pqr
f3: workspace\abc.txt
f4: pqr\abc.txt
f5: D:\java\xyz.txt
f6: D:\java\pqr
f7: D:\java\workspace\abc.txt
f8: D:\java\pqr\abc.txt
f9: D:\java\xyz.txt

While executing the above program, JVM just creates a File class object with the given name as that object state. If the file “xyz.txt” and directory “workspace” are not exist in the current working directory, then also we will not get any exception and it doesn’t create a file or directory.

Conclusion:- File class object creation statement doesn’t create files. To create files we need to use createNewFile() method.

File object creation with complete file or directory path

To create a file object by using a normal file or directory that is existed in another directory we must pass the complete file path. For example:- If a file is located at “D:\java\test\read.txt” then to create a file object we must pass the “D:\java\test” path.

import java.io.File;
public class fileSeperators {
   public static void main(String[] args) {
      File f = new File("D:\java\workspace\read.txt");
      System.out.println("f: "+f);
   }
}

This program gives compile time error: illegal escape character

To separate the parent and child directory in Windows we use file separators “\”, but in java program to represent “\” we need to use the escape sequence character “\\”.

import java.io.File;
public class fileSeperators {
   public static void main(String[] args) {
      File f = new File("D:\\java\\workspace\\read.txt");
      System.out.println("f: "+f);
   }
}

Output:-

f: D:\java\workspace\read.txt

File separators

We can use the above program only in windows. The file separators are platform dependent. In windows we must use “\”, and in Linux, we must use “/”. So, when we are moving our project from Windows to Linux or vice-versa then in all Java files we must change file separators to perform specific separators. Since it is a manual task, it requires a lot of testing so it leads to a lot of maintenance costs. To solve this problem we must have a way to retrieve file separators dynamically specific to the current platform.

In File class we have been given below two variables to retrieve and place path separators dynamically specific to the current platform, they are:-
public static final char separatorChar
public static final char separator

Rewrite the above application to place file separator dynamically.

import java.io.File;
public class fileSeperators {
   public static void main(String[] args) {
      String s = File.separator;
      File f = new File("java"+s+"workspace"+s+"read.txt");
      System.out.println(f);
   }
}

Output in Windows:-

java\workspace\read.txt

Output in Linux:-

java/workspace/read.txt

Java File Methods

File class has below methods to perform different operations on regular files and directories including creating, deleting, and renaming files and directories. There are several methods that are there for file operations, let us categorize them to remember those methods easily.

Methods to create, rename, delete file and directories

Java.io.File class methods to create new file, directory are,

Method with Return TypeDescription
boolean createNewFile()
throws IOException
It creates an empty normal file with the given name in given path.
boolean mkdir()It creates a directory with given name in the given path.
boolean mkdirs()It creats both parent and child directories with given names in the given path.

In the above three methods, If the file/directory already exists in the given path then it returns false else it returns true and creates the file/directory with a given name.

Methods to create temporarily files,

  • public static File createTempFile(String prefix, String suffix, File directory) throws IOException
  • public static File createTempFile(String prefix, String suffix) throws IOException

Learn more:- Java program to create File and directory

Methods to rename the file/directory,

Method with Return TypeDescription
boolean renameTo(File f)It renames the current File with a given name.

Method to delete file or directory represented by the file object,

Method with Return TypeDescription
boolean delete()It deletes the File immediately.
void deleteOnExit()It deletes Files after JVM terminates.

Learn more:- Java program to delete File and directory

Java File class methods for basic file properties

Methods to check basic things about file or directory,

Method with Return TypeDescription
boolean exits()It checks whether a File existed with a given name or not. It returns true if the File exists else returns false.
boolean isFile()It returns true if the given filename denotes a normal file, else it returns false.
boolean isDirectroy()It returns true if the given filename denotes a directory, else it returns false.
long lastModified()It returns the last modified time of the file in milliseconds.
long length()It returns the length of the file (the number of characters) denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.

If the file or directory doesn’t exist then all the above methods return false. langth and last-modified values will be 0.

Created “dir1” folder and “hello.java” file manually in the current working directory. Below programs checks the given file exist or not.

import java.io.File;
public class FileProperties {
   public static void main(String[] args) {

      File f1 = new File("hello.java");
      File f2 = new File("dir1");

      // checking properties for "hello.java" file
      System.out.println(f1.exists()); // true
      System.out.println(f1.isFile()); // true
      System.out.println(f1.isDirectory()); // false
      System.out.println(f1.lastModified()); // 1602122877950
      System.out.println(f1.length()); // 1581
      System.out.println();

      // checking properties for directory "dir1"
      System.out.println(f2.exists()); // true
      System.out.println(f2.isFile()); // false
      System.out.println(f2.isDirectory()); // true
      System.out.println(f2.lastModified()); // 1602122877950
      System.out.println(f2.length()); // 4096
   }
}

The exists() method check with exact passed value. Since strings are case-sensitive so we will get false for the string in different cases. For example:- The actual file name is “hello.java”, so exists() method returns false for “Hello.java”.

File f1 = new File("Hello.java");
System.out.println(f1.exists()); // false

The return type of the length method present in the file class (f.length()) is long but not int because the number of characters present in the file may exceed the int range.

To get the exact last modified time we can use java.sql.Timestamp as shown below,

File f1 = new File("Hello.java");

System.out.println(f1.lastModified());
// returns :- 1602122877950

System.out.println(new java.sql.Timestamp(f1.lastModified()));
// returns :- 2020-10-08 07:37:57.95

Methods to check and set File properties

Methods to set the file properties,

Method with Return TypeDescription
boolean setReadOnly()It set file to readable only, after this method call we can’t write data to this file.
boolean setWritable(boolean writable, boolean ownerOnly)It sets the owner’s or everybody’s write permission
boolean setWritable(boolean writable)It is a convenience method to set the owner’s write permission for this abstract pathname.
boolean setReadable(boolean readable, boolean ownerOnly)It sets the owner’s or everybody’s read permission
boolean setReadable(boolean readable)It is a convenience method to set the owner’s read permission for this abstract pathname.
boolean setExecutable(boolean executable, boolean ownerOnly)It sets the owner’s or everybody’s execute permission
boolean setExecutable(boolean executable)It is a convenience method to set the owner’s execute permission for this abstract pathname.
boolean setLastModified(long time)It set the last-modified time of the file or directory

These setXxx() methods return true if the operation is succeeded, otherwise return false. Both these methods return false if the user does not have permission to change the access permissions of this abstract pathname.

Methods to check file or folder permissions,

Method with Return TypeDescription
boolean canRead()It checks the File is readable or not. It returns true if the File is readable.
boolean canWrite()It checks the File is writeable or not. It returns true if the File is readable.
boolean canExecute()It checks the File is executable or not. It returns true if the File is executable.
boolean isHidden()It checks File is hidden or not. It returns true if the File is hidden.

If the file or directory doesn’t exist then these four methods doesn’t throw any exception rather they returns false.

import java.io.File;
import java.sql.Timestamp;
public class FileProperties {

   public static void main(String[] args) {

      System.out.println("canRead() canWrite()" +
   	  	         " canExecute() isHidden");
		
      // checking properties for "hello.java" file
      File f1 = new File("Hello.java");
      System.out.println(display(f1));

      // setting file permissions
      f1.setReadOnly(); // true
      System.out.println(display(f1));

      f1.setWritable(true); // true
      System.out.println(display(f1));

      f1.setReadable(true); // true
      System.out.println(display(f1));
      
      System.out.println(new Timestamp(f1.lastModified()));
      f1.setLastModified(1692199977950L);
      System.out.println(new Timestamp(f1.lastModified()));
   }

   private static String display(File f) {
   	  return  f.canRead()+"       " +
   	          f.canWrite()+"       " +
   	          f.canExecute()+"       " +
   	          f.isHidden();
   }
}

Output:-

canRead() canWrite() canExecute() isHidden
true       true       false       false
true       false       false       false
true       true       false       false
true       true       false       false
2020-10-08 07:37:57.95
2023-08-16 21:02:57.95

Java File class methods to get file name and its path

Method with Return TypeDescription
String getName()Returns the relative path of the File, i.e. only Filename.
String getAbsolutePath()Returns the absolute path of the File, i.e. complete File path including name, in the String object format.
File getAbsoluteFile()Returns absolute path of the file in File object format.
String getCanonicalPath()
throws IOException
It returns absolute path in String object format with system depended drive name.
File getCanonicalFile()
throws IOException
It returns absolute path in File object format with system depended drive name.
boolean isAbsolute()It returns true if the File is created with absolute path
String getParent()It returns parent directory name as String object, null if it doesn’t have parent.
File getParentFile()It returns parent directory name as File object, null if it doesn’t have parent.
String getPath()It returns path in String form.

Methods to check spaces,

Method with Return TypeDescription
long getTotalSpace()Return size of partition in bytes.
long getFreeSpace()Return number of unallocated bytes on the partition.
long getUsableSpace()The number of available bytes on the partition.

The above three methods return 0L if the abstract path doesn’t have name a partition or if the size can’t be obtained. The systems where information of available bytes on the partition is not available, then getUsableSpace() method will be equivalent to call to getFreeSpace().

import java.io.File;
import java.io.IOException;
public class FileProperties {
   public static void main(String[] args) throws Exception {
      
      File f1 = new File("input.txt");
      System.out.println(f1.exists());
      System.out.println(f1.getName());
      System.out.println(f1.getAbsolutePath());
      System.out.println(f1.getAbsoluteFile());
      System.out.println(f1.getCanonicalPath());
      System.out.println(f1.getCanonicalFile());
      System.out.println(f1.isAbsolute());
      System.out.println(f1.getParent());
      System.out.println(f1.getParentFile());
      System.out.println(f1.getPath());
      System.out.println(f1.getTotalSpace());
      System.out.println(f1.getFreeSpace());
      System.out.println(f1.getUsableSpace());

      // creating object with absolute path
      File f2 = new File("/home/user/workspace/java/dir2");
      System.out.println(f2.getName());
      System.out.println(f2.isAbsolute());
   }
}

Output:-

true
input.txt
D:\java\input.txt
D:\java\input.txt
D:\java\input.txt
D:\java\input.txt
false
null
null
input.txt
198003650560
124712775680
124712775680
dir2
false

Java File class Methods to list files and subdirectories in a given directory

Method with Return TypeDescription
String[] list()It returns all File names as String objects using String array.
String[] list( FilenameFilter filter)It returns all File names whose name are matched with given filter as String objects using String array.
File[] listFiles()It returns all File names as File objects using File array.
File[] listFiles( FilenameFilter filter)It returns all File names whose names are matched with the given filter as File objects using File array.
File[] listFiles( FileFilter filter)It returns all File names whose names are matched with given FileFilter as File objects using File array.

In above five methods:- The array will be empty if the directory is empty. It returns null if abstract pathname is not a directory, or if an I/O error occurs.

File[] listRoots()It returns An array of File objects denoting the available file system roots, or null if the set of roots could not be determined. The array will be empty if there are no file system roots.

Learn more:- Java program to get files and directory

Other Methods of File class in Java

Method to print file object state,

int compareTo(File pathname)Compare the File name lexicographically. Returns 0 for same, 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
Path toPath()Return a path constructed from this abstract path
String toString()return getpath()
boolean equals(Object obj)Call comareTo() if passed value is instanceof File else return true.

Method to convert file normal path to URL to URI,

  • public java.net.URL toURL() throws java.net.MalformedURLException; // This method is deprecated
  • public java.net.URI toURI();

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *