Java Examples - Create File

Java Examples

The following example demonstrates using the File() constructor of the File class and the file.createNewFile() method to create a new file.

Main.java file

import java.io.File; import java.io.IOException; public class Main { public static void main(String[] args) { try{ File file = new File("C:/myfile.txt"); if(file.createNewFile()) System.out.println("File created successfully!"); else System.out.println("Error, the file already exists."); } catch(IOException ioe) { ioe.printStackTrace(); } } }

The output from running the above code is:

File created successfully!

Java Examples

Other Extensions