Java File class tutorial with examples will help you understand how to use Java File class in an easy way. The File in Java represents the file and directory path names. Different operating systems use system dependent strings to name the file and directories. The File class represents these file and directory paths in an abstract manner.
The pathnames denoted by the File object may be relative or absolute. It may be different for different operating systems, for example, a file name starting with ‘/’ in the Unix environment is always an absolute path, while in Windows it starts with a drive letter like C: or D:.
The File class in Java provides various methods to create, read and delete the files and directories. Here are some of the very useful methods provided by the File class.
Java File class methods
How to check if the File object points to a file or a directory?
The File class provides isFile
and isDirectory
methods to check if this file object is a file or a directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
File file = new File("E:/temp1.txt"); File dir = new File("E:/temp1"); /* * To check if the File object is a file, use * the isFile method. */ //this will return true since E:/temp1.txt is a file System.out.println( file.isFile() ); /* * To check if the File object is a directory, use * the isDirectory method. */ //this will return true since E:/temp1 is a directory System.out.println( dir.isDirectory() ); |
Output
1 2 |
false true |
These method returns false if the file denoted by the File object does not exist.
How to check if a file or directory is hidden using the isHidden method?
The isHidden
method returns true if the file denoted by this file object is hidden. In *nix systems, hidden files and directories start with a . (dot). For Windows, the file is hidden if the file is marked as hidden in the operating system.
1 2 3 4 5 6 7 8 |
File file = new File("E:/hidden_file.txt"); /* * To check if the file is hidden or visible, use * the isHidden method. */ //this will return true as E:/hidden_file.txt is hidden System.out.println( file.isHidden() ); |
Output
1 |
true |
The isHidden
method returns false if the file does not exist. Please refer to how to make file hidden in Java example to know about making a file or directory hidden in any operating system.
How to check if the file or directory exists using the exists method?
The exists
method returns true if the file or directory denoted by this File object exists. It returns false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//path of the file File file = new File("C:/temp.txt"); //path of the directory File dir = new File("C:/temp"); /* * To check if the file or directory exists, use * the exists method */ //this will return true if you have C:/temp.txt file. System.out.println( file.exists() ); //this will return true if you have C:/temp directory. System.out.println( dir.exists() ); |
Output
1 2 |
true true |
The output could be different for you if you do not have the mentioned file or directory in your system. Please also note that the exists
method throws SecurityException if the security manager denies the read access to the specified file or directory.
How to get the parent directory name for a file using the getParent and getParentFile methods?
The getParent
method returns a string containing the parent directory of this file object. Similarly, the getParentFile
method returns a parent File object of this file object. Both of these methods return null if this file object does not have a parent.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
File file = new File("E:/temp1/temp1.txt"); /* * To get the parent directory name of a file, use the * getParent method */ String strParentDirectory = file.getParent(); System.out.println( "Get parent directory: " + strParentDirectory ); /* * To get the parent directory File object, use the * getParentFile method. */ File fParentDir = file.getParentFile(); System.out.println( "Get parent directory: " + fParentDir.getPath() ); File file1 = new File("C:/"); //this will return null, as C:/ is a root and does not have a parent System.out.println( "Get parent directory: " + file1.getParent() ); |
Output
1 2 3 |
Get parent directory: E:\temp1 Get parent directory: E:\temp1 Get parent directory: null |
How to get a file name from the File object using the getName method?
The getName
method returns a string containing the file or directory name from the path denoted by this file object.
1 2 3 4 5 6 7 8 9 10 11 |
File file = new File("E:/temp1/temp1.txt"); /* * To get a file name from File object, use the * getName method. */ System.out.println("Get file name from the path: " + file.getName()); File dir = new File("E:/temp1/"); System.out.println("Get directory name from the path: " + dir.getName()); |
Output
1 2 |
Get file name from the path: temp1.txt Get directory name from the path: temp1 |
Please refer to how to get file extension in Java example to learn about how to get the extension.
How to get a file path from the File object using the getPath method?
The getPath
method of the File class returns a string containing the path of the file or directory denoted by this File object.
1 2 3 4 5 6 7 8 9 10 11 |
File file = new File("E:/temp1/temp1.txt"); /* * To get a file path from File object, use the * getPath method. */ System.out.println("Get file path: " + file.getPath()); File dir = new File("E:/temp1/"); System.out.println("Get directory path: " + dir.getPath()); |
Output
1 2 |
Get file path: E:\temp1\temp1.txt Get directory path: E:\temp1 |
The getPath
method is particularly useful when we want to get the full path of the file or directory.
How to check read, write, and execute permissions for a file or directory?
The File class provides canRead
, canWrite
and canExecute
methods to check whether the file or directory has read, write and execute permissions respectively. These methods return true if the application has read, write, or execute permission for the given the file or a directory. Please note that these methods return false if the specified file or directory does not exist in the file system.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
//path of the file File file = new File("E:/temp.txt"); //path of the directory File dir = new File("C:/temp"); /* * To check read, write or execute permissions * use the canRead, canWrite, and canExecute methods. */ //always make sure to check if the file exists first System.out.println("Check file permissions: "); if(file.exists()){ System.out.println( "File Read Permission: " + file.canRead()); System.out.println( "File Write Permission: " + file.canWrite()); System.out.println( "File Execute Permission: " + file.canExecute()); }else{ System.out.println( "File does not exists" ); } //always make sure to check if the directory exists first System.out.println("Check directory permissions: "); if(dir.exists()){ System.out.println( "Directory Read Permission: " + dir.canRead()); System.out.println( "Directory Write Permission: " + dir.canWrite()); System.out.println( "Directory Execute Permission: " + dir.canExecute()); }else{ System.out.println( "Directory does not exists" ); } |
Output
1 2 3 4 5 6 7 8 |
Check file permissions: File Read Permission: true File Write Permission: true File Execute Permission: true Check directory permissions: Directory Read Permission: true Directory Write Permission: true Directory Execute Permission: true |
Note that the output may be different for you if you do not have the specified file or do not have any particular permission.
How to set read, write, and execute permissions for a file or a directory?
1. How to set read permission for file or directory?
The setRedable
method of the File class sets the read permission for this file object.
1 |
public boolean setRedable(boolean redable, boolean ownerOnly) |
If the readable parameter is true, the read permission is given for the file, if false, read permission is disallowed. If the ownerOnly parameter is true, the permission change is applied to the owner of file only. If it is false, the change is applied to everyone.
1 2 3 4 5 6 7 8 9 10 11 |
File file = new File("E:/temp.txt"); //always make sure that the file exists first if(file.exists()){ /* * To make file readable, use the * setReadable method */ System.out.println( file.setReadable(true, false) ); } |
Output
1 |
true |
The setReadable
method returns true if and only if the operation is succeeded. It returns false if the user does not have access to the file or operating system does not support the read permissions for the file or directory. Additionally, it throws SecurityException if the security manager denies the read access to the specified file or directory.
2. How to set write permission for a file or directory?
The setWritable
method of the File class sets the write permission for this file object.
1 |
public boolean setWritable(boolean writable, boolean ownerOnly) |
If the writable parameter is true, the write permission is given for the file, if false, write permission is disallowed. If the ownerOnly parameter is true, the permission change is applied to the owner of the file only. If it is false, the change is applied to everyone.
1 2 3 4 5 6 7 8 9 10 11 |
File file = new File("E:/temp.txt"); //always make sure that the file exists first if(file.exists()){ /* * To make file or directory writable, use the * setWritable method */ System.out.println( file.setWritable(true, false) ); } |
Output
1 |
true |
How to make a file read only?
Use the setWritable
method and pass false as the writable parameter to make the file read only in Java.
1 2 3 4 5 6 7 8 9 10 |
File file = new File("E:/temp.txt"); //always make sure that the file exists first if(file.exists()){ /* * To make file or directory read only, pass false * in the setWritable method */ System.out.println( file.setWritable(false, false) ); } |
The setWritable
method returns true if and only if the operation is succeeded. It returns false if the user does not have access to the file. Additionally, it throws SecurityException if the security manager denies the write access to the specified file or directory. Here is the complete example of how to make file read-only in Java.
3. How to set execute permission for a file or directory?
The setExecutable
method sets the execute permission for this file object.
1 |
public boolean setExecutable(boolean executable, boolean ownerOnly) |
If the executable parameter is true, the execute permission is given for the file, if false, the execute permission is disallowed. If the ownerOnly parameter is true, the permission change is applied to the owner of the file only. If it is false, the change is applied to everyone.
1 2 3 4 5 6 7 8 9 10 |
File file = new File("E:/temp.txt"); //always make sure that the file exists first if(file.exists()){ /* * To set execute permission for the file or a directory, use the * in the setExcutable method */ System.out.println( file.setExecutable(true, false) ); } |
Output
1 |
true |
The setExecutable
method returns true if and only if the operation is succeeded. It returns false if the user does not have access to the file permissions or operating system does not support the execute permissions for the file or directory. Additionally, it throws SecurityException if the security manager denies the write access to the specified file or directory.
How to check the last modified time of a file or a directory?
The lastModified
method of the File class returns the last modified time of this file object. This method returns a long value representing the time in milliseconds since epoch i.e. 00:00:00 GMT, January 1, 1970.
1 2 3 4 5 6 7 8 9 10 11 12 |
File file = new File("E:/temp.txt"); if(file.exists()){ /* * To get the last modified time of a file or directory, use the * lastModified method. */ long lastModifiedTime = file.lastModified(); //convert it to date System.out.println( "File last modified on: " + new Date( lastModifiedTime ) ); } |
Output
1 |
File last modified on: Tue Sep 17 12:34:52 IST 2019 |
How to change the last modified time of a file or a directory?
The setLastModified
method of the File class sets the last modified time of a file or a directory. The below given example shows how to set the file’s last modified time to the current time or now.
1 2 3 4 5 6 7 8 9 10 11 12 |
File file = new File("E:/temp.txt"); if(file.exists()){ /* * To set the last modified time of a file or directory, use the * setLastModified method. */ //this will set the last modified time of the file to current time or now file.setLastModified( new Date().getTime() ); System.out.println("File last modified time: " + new Date(file.lastModified())); } |
Output
1 |
File last modified time: Tue Sep 17 13:57:04 IST 2019 |
How to create a new file using the createNewFile and createTempFile methods?
The crateNewFile
create a new empty file at the specified location. It returns true if the file does not already exist and it is created. It returns false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//file to be created File file = new File("E:/temp1.txt"); /* * To create a new empty file, use the * createNewFile method. */ try { boolean created = file.createNewFile(); System.out.println("New file created?: " + created); } catch (IOException e) { e.printStackTrace(); } |
Output
1 |
New file created?: true |
The createNewFile
method throws IOException in case of any IO errors. It also throws SecurityException if the security manager denies the write access to the file.
Similarly, to create a new temporary file, use the createTempFile
method.
1 |
public static File createTempFile(String filePrefix, String fileSuffix) |
This method creates a temporary file in the operating system’s default temp directory using the specified suffix and prefix strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/* * To create a new temporary file in the OS temp directory, use the * createTempFile method. */ try { File tempFile = File.createTempFile("Java", "TempFile.tmp"); System.out.println("New temp file created at: " + tempFile.getPath()); } catch (IOException e) { e.printStackTrace(); } |
Output
1 |
New temp file created at: C:\Users\RV\AppData\Local\Temp\Java1951417260032824787TempFile.tmp |
The above method creates a new temp file in the default temp directory. If you want to create a new temp file in the specified directory, use the overloaded createTempFile
method with the File argument.
1 |
public static File createTempFile(String prefix, String suffix, File directory) |
The below given example creates a new temp file in the specified directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/* * To create a new temporary file in the specified directory, use the * createTempFile method. */ try { File tempFile = File.createTempFile("Java", "TempFile.tmp", new File("C://temp")); System.out.println("New temp file created at: " + tempFile.getPath()); } catch (IOException e) { e.printStackTrace(); } |
Output
1 |
New temp file created at: C:\temp\Java7918184567102614768TempFile.tmp |
Refer to a complete example of how to create a new empty file in Java for more details.
How to create a new directory using the mkdir and mkdirs methods?
The mkdir
method creates a new directory denoted by this file object path. It returns true if the directory does not already exist and it is created. It returns false otherwise.
1 2 3 4 5 6 7 8 9 10 |
File dir = new File("E:/tempdir"); /* * To create a new directory, use the mkdir method */ //always check if the directory exists first if(!dir.exists()){ boolean dirCreated = dir.mkdir(); System.out.println("New directory created: " + dirCreated); } |
Output
1 |
New directory created: true |
The mkdir
method throws SecurityException if the security manager does not permit the directory to be created.
If you want to create the specified directory along with all the non-existent parent directories, use the mkdirs
method. For example, if you want to create directory like D:/dir1/dir2/Java and if the dir1 or dir2 or both of them do not exist, the mkdir
method does not work because the parent directories do not exist. In this case, you need to use the mkdirs
method.
1 2 3 4 5 6 |
/* * To make a new directory along with all the required * parent directories, use the mkdirs method */ File dir = new File("E:/dir1/dir2/tempdir"); System.out.println( "New directories created?: " + dir.mkdirs()); |
Output
1 |
New directories created?: true |
How to delete a file or directory using the delete and deleteOnExit methods?
The delete
method of the File class deletes the file denoted by this file object. It returns true if the file or directory is deleted successfully.
1 2 3 4 5 |
//file to be deleted File file = new File("E:/temp1.txt"); boolean isDeleted = file.delete(); System.out.println("Is file deleted?: " + isDeleted); |
Output
1 |
true |
How to delete a directory?
If the file object points to a directory, it must be empty for the delete
method to work. If it is not, the delete
method does not delete the directory and returns false.
The below given code tries to delete a directory that is not empty. The delete
method returns false in this case.
1 2 3 4 5 6 |
//directory to be deleted File file = new File("E:/temp1"); //the directory is not empty, so this will return false boolean isDeleted = file.delete(); System.out.println("Is directory deleted?: " + isDeleted); |
Output
1 |
Is directory deleted?: false |
How to delete a directory recursively (using the recursive method)?
So in order to delete a directory, we first need to go to all the subdirectories and empty them and then we can delete a directory in Java. Below given code shows how to delete a directory recursively in Java (i.e. delete a directory using recursive function or method).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class Example { public static void main(String[] args) { //directory to be deleted File file = new File("E:/temp1"); //call the recursive function delete(file); } public static void delete(File file){ /* * If this is a directory, get the * children and delete them first */ if(file.isDirectory()){ //get the directory children for(File f : file.listFiles()){ //call the function recursively delete(f); } } //if this is a file, directly delete it System.out.println( file.getPath() + " is deleted: " + file.delete()); } } |
Output
1 2 3 4 5 |
E:\temp1\temp.txt is deleted: true E:\temp1\temp2\temp2.txt is deleted: true E:\temp1\temp2\temp3 is deleted: true E:\temp1\temp2 is deleted: true E:\temp1 is deleted: true |
The delete
method throws SecurityException if the security manager denies delete access to the file or directory.
The above given delete
method immediately deletes a file or directory. If you want to delete a file or directory when virtual machine exits, use the deleteOnExit
method. For example, if your program runs on tomcat server, then the file will be deleted when the server stops.
1 2 3 4 5 6 7 8 9 |
//file to be deleted File file = new File("E:/temp1"); /* * This will delete the file when * the virtual machine exits (for example * when server is stopped) */ file.deleteOnExit(); |
The files will be deleted in the reverse order of the delete requests. Please note that the deletion will only happen when the virtual machine exits in normally. If the virtual machine is terminated due to an unrecoverable error, the file is not deleted. Plus, you cannot rollback the delete request once it is made, so take care while calling the deleteOnExit
method.
How to list directory contents using the list and listFiles methods?
The list
method returns a String array containing child file and directory names of this file object. Similarly, the listFiles
method returns a File object array containing the children of this file object.
1 2 3 4 5 6 7 8 9 10 |
File dir = new File("E:/temp1"); /* * To get the directory children, use the * listFiles method. */ File[] children = dir.listFiles(); for(File file : children){ System.out.println( file.getPath() ); } |
Output
1 2 |
E:\temp1\temp2 E:\temp1\temp1.txt |
As you can see from the output, the above code does not go into a subdirectory. It prints only first level child file names. If you want to list all the child files and directories recursively, refer to below given code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class Example { public static void main(String[] args) { File dir = new File("E:/temp1"); //call the recursive function listFiles(dir); } /* * This function recursively lists the directoy contents */ public static void listFiles(File file){ /* * If this is a directory, list the * contents */ if(file.isDirectory()){ for(File f : file.listFiles()){ //call recursive function for each child listFiles(f); } } //if it is file, print name of it System.out.println( file.getPath() ); } } |
Output
1 2 3 4 5 6 |
E:\temp1\temp2\temp2.txt E:\temp1\temp2\temp3\temp3.txt E:\temp1\temp2\temp3 E:\temp1\temp2 E:\temp1\temp1.txt E:\temp1 |
How to get a file size using the length method?
The length
method of the File class returns the size of the file denoted by this File object. This method only works for file, the result is unspecified if the file object is referring to a directory.
1 |
public long length() |
This method returns file size in bytes.
1 2 3 4 |
File file = new File("E:/temp.txt"); long fileSize = file.length(); System.out.println("File size in bytes: " + fileSize); |
Output
1 |
File size in bytes: 36 |
Please refer to the detailed example on how to get file size in KB, MB, and GB in Java to know more.
How to use getTotalSpace, getFreeSapce, and getUsableSpace methods?
1. How to get the total size of a drive or a partition using the getTotalSpace method?
The getTotalSpace
method returns the size of the partition or a drive (in case of Windows).
1 |
public long getTotalSpace() |
This method returns the size of the partition or a drive in bytes and 0 if this file object does not name a drive/partition.
1 2 3 4 5 6 7 |
/* * To get the size of a drive or parition, use the * getTotalSpace method */ File file = new File("C:"); System.out.println("Total size of C Drive: " + file.getTotalSpace() + " bytes"); System.out.println("Total size of C Drive: " + file.getTotalSpace()/(1024 * 1024 * 1024) + " GB"); |
Output
1 2 |
Total size of C Drive: 154155347968 bytes Total size of C Drive: 143 GB |
2. How to get the free space of a drive or a partition using the getFreeSpace method?
The getFreeSpace
method returns the number of unallocated bytes in the given drive or a partition. In other words, it returns the available space in a drive or a partition. It returns 0 if this file object does not name a drive/partition.
1 2 3 4 5 6 7 |
/* * To get the free space of a drive or partition, use the * getFreeSpace method */ File file = new File("C:"); System.out.println("Total size of C Drive: " + file.getTotalSpace()/(1024 * 1024 * 1024) + " GB"); System.out.println("Free space in C Drive: " + file.getFreeSpace()/(1024 * 1024 * 1024) + " GB"); |
Output
1 2 |
Total size of C Drive: 143 GB Free space in C Drive: 60 GB |
3. How to get the usable space of a drive or a partition using the getUsableSpace method?
The getUsableSpace
method returns total usable bytes available in the drive or partition. This method provides a more accurate number of the available space as compared to the getFreeSpace
method as this method also considers operating system restrictions.
1 2 3 |
File file = new File("C:"); System.out.println("Total size of C Drive: " + file.getTotalSpace()/(1024 * 1024 * 1024) + " GB"); System.out.println("Usable space in C Drive: " + file.getUsableSpace()/(1024 * 1024 * 1024) + " GB"); |
Output
1 2 |
Total size of C Drive: 143 GB Usable space in C Drive: 60 GB |
Below given additional examples will help you understand Java file concepts in more detail.
Java File Examples
- How to create new empty file in Java
- How to get size of file in Java
- How to create a directory in Java
- How to make file hidden in Java
- How to make file read only in Java
- How to get file extension in Java
- How to check if file exists in Java
- How to delete a file or delete a directory in Java
- How to get absolute path of a file in Java
- How to fix java.io.FileNotFoundException (access is denied)
- How to convert InputStream to String
References:
Java File class Javadoc
Please let me know if you liked the Java File class tutorial with examples in the comments section below.