Create a File
Use the createNewFile() method to create a file. The method returns a Boolean value: true, if the file was successfully created and false, if the file already exists. Note that the method is usually enclosed with try…catch block. This is necessary because it throws an IOException if an error occurs (if the file is not created for some reason).
Example
import java.io.File; //Import the File class import java.io.IOException; //Import the IOException class to handle errors public class CreateFile { public static void main(String args[]){ try { File myFile = new File("newfile.txt"); if(myFile.createNewFile()){ System.out.println("File created : "+myFile.getName()); } else { System.out.println("File already exists"); } } catch (IOException e) { System.out.println("An error occured"); e.printStackTrace(); } } }
Output
File created : newfile.txt
To create a file in specific directory (requires permission), specify the path of the file with double backslashes to escape the “\” character (in Windows). For Mac, directly give the path.
Example
File myFile = new File("C:\\Users\\SparkDatabox\\newfile.txt");
Get File
Information
In the above example code, we created a new file. We will use the File methods to get the information of the File.
Example
In the below example, with the help of File Methods, we get the information of the file:
import java.io.File; //Import the File class import java.io.IOException; //Import the IOException class to handle errors public class CreateFile { public static void main(String args[]){ File myFile = new File("newfile.txt"); if(myFile.exists()){ System.out.println("File name : "+myFile.getName()); System.out.println("Absolute Path : "+myFile.getAbsolutePath()); System.out.println("Is Readable : "+myFile.canRead()); System.out.println("Is Writeable : "+myFile.canWrite()); System.out.println("File size in bytes : "+myFile.length()); } } }
Output
File name : newfile.txt Absolute Path : C:\Users\SparkDatabox\workspace\Core_java_practices\newfile.txt Is Readable : true Is Writeable : true File size in bytes : 79