Java File Class Tutorial with Examples

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.

Output

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.

Output

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.

Output

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.

Output

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.

Output

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.

Output

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.

Output

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.

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.

Output

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.

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.

Output

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.

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.

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.

Output

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.

Output

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.

Output

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.

Output

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.

This method creates a temporary file in the operating system’s default temp directory using the specified suffix and prefix strings.

Output

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.

The below given example creates a new temp file in the specified directory.

Output

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.

Output

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.

Output

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.

Output

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.

Output

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).

Output

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.

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.

Output

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.

Output

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.

This method returns file size in bytes.

Output

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).

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.

Output

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.

Output

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.

Output

Below given additional examples will help you understand Java file concepts in more detail.

Java File Examples

References:
Java File class Javadoc

Please let me know if you liked the Java File class tutorial with examples in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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