Java.io.File.createNewFile() Method
Description
The java.io.File.createNewFile() method atomically creates a new file named by this abstract path name. FileLock facility should be used instead of this method for file-locking as the resulting protocol cannot be made to work reliably.
Declaration
Following is the declaration for java.io.File.createNewFile() method:
public boolean createNewFile()
Parameters
NA
Return Value
This method returns true, if the named file does not exist and was successfully created. The method returns false if the file exists.
Exception
IOException -- If an I/O error occurs
SecurityException -- If SecurityManager.checkWrite(java.lang.String) method denies write access to the file
Example
The following example shows the usage of java.io.File.createNewFile() method.
package com.tutorialspoint;
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
File f = null;
boolean bool = false;
try{
// create new file
f = new File("test.txt");
// tries to create new file in the system
bool = f.createNewFile();
// prints
System.out.println("File created: "+bool);
// deletes file from the system
f.delete();
// delete() is invoked
System.out.println("delete() method is invoked");
// tries to create new file in the system
bool = f.createNewFile();
// print
System.out.println("File created: "+bool);
}catch(Exception e){
e.printStackTrace();
}
}
}
Let us compile and run the above program, this will produce the following result:
File created: false delete() method is invoked File created: true