On this document we will be showing a java example on how to use the createNewFile() method of File Class. This method is basically in place to atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.


  • IOException – If an I/O error occurred
  • SecurityException – If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the file

Method Syntax

public boolean createNewFile() throws IOException

Method Argument

Data Type Parameter Description

Method Returns

This method returns boolean, true if the named file does not exist and was successfully created; false if the named file already exists. This is in place so that you have a way to determine if the creation of file is successful or not and act accordingly.


Requires Java 1.2 and up

Java File createNewFile() Example

Below is a java code demonstrates the use of createNewFile() method of File class. The example presented might be simple however it shows the behaviour of the createNewFile() method of File class. Basically we called this method and we put a check on the returned value to check if the creation of new file is successful or not.

The example provided below shows that on the first run, the file has been created successfully while on the second run it failed. That is because the file is already created on the first run, thus succeeding run will definitely fail as describe on the earlier part of this document.



 * This example source code demonstrates the use of  
 * createNewFile() method of File class.

public class FileCreateNewFileExample {

	public static void main(String[] args) {
		// initialize File object
		File file = new File("C:javatutorialhqinput.txt");		
		boolean result;
		try {
			// create a new file
			result = file.createNewFile();
			// test if successfully created a new file
				System.out.println("Successfully created "+file.getCanonicalPath());
				System.out.println("Filed creating "+file.getCanonicalPath());
		} catch (IOException e) {

Sample Output

Below is the sample output when you run the above example.

java lang File createNewFile() example output