Java File createNewFile() Method
Example
Create a new file, then try to create it again:
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
File myFile = new File("filename.txt");
myFile.delete(); // Delete the file if it already exists
System.out.println(myFile.createNewFile());
System.out.println(myFile.createNewFile());
}
}
Definition and Usage
The createNewFile() method creates a new, empty file.
If the file already exists, nothing happens and the method returns false. It never replaces a file that is already there.
Tip: To write text to the new file, use the FileWriter class.
Syntax
public boolean createNewFile()
Parameter Values
None.
Technical Details
| Returns: | true if the file was created, false if it already exists. |
|---|---|
| Throws: | IOException - if the file cannot be created, for example because a folder in the path does not exist. |
Related Pages
❮ File Methods