The java.io package is useful when you want to perform any type of input or output operation.It contains different classes for performing input and output operations in Java.Here we will see how to Create file in Java using File class.
It contains the File class for performing file and directory related input/output operations.
To create a new following steps could be used
1.Import the file class by using
import java.io.File;
2.Declare a variable to File type.Pass the path and the name of the file you want to create.
String path="exampleFile.txt"; File file= new File(path);
3.Create a new file by calling the createNewFile() method.This method returns boolean if the file is created and returns false if the file is not created.Also it throws the IOException if there is any exception.You should enclose the call to createNewFile() method in try catch block otherwise you will get compile time error.
try { if(file.createNewFile()) System.out.println("file created"); else System.out.println("unable to create file"); } catch(IOException e) { System.out.println("exception occured"); }
Complete example:
import java.io.File; class FileExample{ String path="exampleFile.txt"; File file= new File(path); try { if(file.createNewFile()) System.out.println("file created"); else System.out.println("unable to create file"); } catch(IOException e) { System.out.println("exception occured"); } }
Leave a Reply