How to Create a File in Java Programming
Creating a file in Java is extremely easy. To create a file in Java we use File.createNewFile() method which returns a boolean value true if the file is created and false if the file is already existing or the the file creation operation fails.
No Parameters supplied.
boolean: ‘true’ or ‘false’
- true: if file created successfully
- false: if file is already existing or the operation fails due to any reason
- IOException: If any I/O error occurs
- SecurityException: If write access to the disk is denied.
Below is an example Java code to create a file on the disk.
public class CreateAFileInJava
public static void main(String args)
//Initialize the location of the file
String fileLoc = "c:\\mytestfile.txt";
//Create a new File Object
File myFile = new File(fileLoc);
//Physically the file is created and simultaneously we are checking the
//returned result from the method createNewFile()
System.out.println("My New File Created.");
System.out.println("File already exists.");
catch (IOException e)
Above example will output : My New File Created if the operation is Successful else it will return File already Exists. Hope this tutorial helped you.