Skip to content

Create a new empty File in Java Example

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

How to create a new file in Java?

There are a couple of ways you can create a new empty file in Java along with the required parent directories.

1) Create a new file using the java.io.File class

The createNewFile method of the File class can be used to create a new empty file.

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

Output

Note: If the file denoted by the path already exists, the createNewFile method returns false. So If you run the above program a second time, it will print false because it had created the given file in the first run of the program.

ThecreateNewFile method does not create necessary parent directories. If the required directories do not exist, this method will throw an  IOException. Consider the below-given code.

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

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

2) Using FIleUtils class of Apache Commons IO

If you are using the Apache Commons library, you can use the touch method of the FileUtils class to create a 0-byte new empty file.

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

This example is a part of the Java File class tutorial with examples.

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

About the author

Leave a Reply

Your email address will not be published.