The createNewFile() method creates a new and empty file with specified name. This operation succeeded when the name does not yet exist. Checking for the existence of the file and creation of the file are atomic operations. Note that this method should not be used for file-locking.
2. Method signature
Parameters:
method does not take any parameter
Returns
true - if the file does not exists already and was created successfully
Throws
IOException - if any of I/O error occurred
SecurityException - when we do not have access to the file
3. Examples
3.1. Create a new file in the /tmp directory
The output:
In case the file already exists, method f.createNewFile() will return false and we will get the following result:
3.2. Create a new file and check common parameters
The output:
4. Conclusion
In this article we presented File.createNewFile() a method that can be used to create a new file in an atomic way. Method checks if a file with a given name already exists before creating a new file, and this a single operation with respect to all other filesystem activities that might affect the file.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}