Java IO

Create a new empty File in Java Example

This example shows how to create a new empty file in Java either using createNewFile() method of File class or Apache Commons IO library.

How to create a new file in Java?

A new empty file can be created in Java along with the required parent directories. Here are two approaches.

1) Create new file using class

createNewFile() method of File class can be used to create new empty file.

This method returns true if the file does not exists and was created successfully. It returns false if the file already existed. This method may throw IOException in the event of error condition. This method can also throw java.lang.SecurityException, if the write access is denied.


Note: If the file denoted by the path already existed, createNewFile() method returns false. So If you run the program second time, it will print false because it had created the said file in the first run of the program.

createNewFile() method does not create necessary directories. If the required directories do not exist, this method will throw IOException. Consider below given code.

If “dir” directory does not exist, the program will throw IOException like given below.

Always make sure that the required directories are created using mkdirs() method before attempting to create a new file like given below.

2) Create new file using FIleUtils class of Apache Commons IO

Use touch() method of Apache Commons FileUtils class to create 0 byte new empty file.

touch() method has same behavior as Unix touch command. If the file already exists, it modifies the file’s timestamp. If file does not exists, it creates it along with the required parent directories (from version 1.3 onwards)

Please let us know your views in the comments section below.