In this post we will see an example on how we can create file in java.
We will use the File.createNewFile() method.
File.createNewFile() creates a new empty file if a file doesn’t exists already in the given path.
createNewFile() returns “true” if file is created successfully.
If we try to create a file that already exists in the given path then createNewFile() returns false.
Example : Create File in java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.kscodes.sampleproject; import java.io.File; import java.io.IOException; public class FileHandling { /** * @param args */ public static void main(String[] args) throws IOException { createFile(); } public static void createFile() throws IOException { File file = new File("C:\\testFile.txt"); boolean fileCreated = file.createNewFile(); if (fileCreated) { System.out.println("File created successfully"); } else { System.out.println("File couldn't be created"); } } } |
When performing any operation on File, you will need to handle the IOException exception.
You can get more details on the File API here