In this article, we are going to present how to create a new file in Java. There are several ways to do it, using core Java IO and NIO methods or external libraries like Apache Commons IO or Google Guava.
This article is a part of the Java IO Tutorial.
2. Create a file with
We can create an empty file using File.createNewFile() method available in standard Java I/O API. The method returns
- true - when a file has been created successfully,
- false - when a file with the given name already exists - in that case, the method will not do anything (it will not override the original content, also timestamp will stay untouched).
3. Create a file with
JDK 7 gives a new approach to creating files. Java NIO API provides the Files.createFile() method that creates a new file with an empty content. Note that if a file with given name already exists the method will throw
4. Create a file with
java.io.FileOutputStream is another indirect method to create a new file in Java. Because the method was not originally designed to create new files, you should use it in situations when you want to fill a newly created file with some input data.
5. Create a file with
Google Guava library
Although it is not recommended if you want to you can use external libraries to create a new file. In
Google Guava library you can create a file in a single line using
Files.touch() method. The method works similar to
touch command in
Linux - it creates an empty file or updates the last updated timestamp.
6. Create a file with
Apache Commons IO library
Apache Commons IO library comes with
FileUtils.touch() method that provides the similar functionality to the Guava
Files.touch(). Note that if a file already exists it will not throw any exception.
In this tutorial, we described several ways to create an empty file in Java. We use core Java classes available under the
java.nio packages and two external libraries:
Examples from this article can be found under GitHub repository.