JavaCreate Files
Create a File
In Java, you can create a new file with thecreateNewFile() method from theFile class.
This method returns:
true- if the file was created successfullyfalse- if the file already exists
Note that the method is enclosed in atry...catch block. This is necessary because it throws anIOException if an error occurs (if the file cannot be created for some reason):
Example
import java.io.File; // Import the File classimport java.io.IOException; // Import IOException to handle errorspublic class CreateFile { public static void main(String[] args) { try { File myObj = new File("filename.txt"); // Create File object if (myObj.createNewFile()) { // Try to create the file System.out.println("File created: " + myObj.getName()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); // Print error details } }}The output will be:
File created: filename.txtExplanation: The program tries to create a file calledfilename.txt. If the file does not exist, it will be created and a success message is printed. If the file already exists, you will see the message"File already exists." instead.
Note: ThecreateNewFile() method only creates anempty file. It does not add any content inside. You will learn how towrite text to files in the next chapter.
Create a File in a Specific Folder
To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt

