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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
/* Create new empty file This Java example shows how to create new empty file at specified path using createNewFile method of Java File class. */ import java.io.*; public class CreateNewEmptyFile { public static void main(String[] args) { //create File object File file = new File("C://demo.txt"); /* * To actually create a file specified by a pathname, use * boolean createNewFile() method of Java File class. * * This method creates a new empty file specified if the file with same * name does not exists. * * This method returns true if the file with the same name did not exist and * it was created successfully, false otherwise. */ boolean blnCreated = false; try { blnCreated = file.createNewFile(); } catch(IOException ioe) { System.out.println("Error while creating a new empty file :" + ioe); } System.out.println("Was file " + file.getPath() + " created ? : " + blnCreated); /* * If you run the same program 2 times, first time it should return true. * But when we run it second time, it returns false because file was already * exist. */ } } /* Output would be Was file C:demo.txt created ? : true */ |
Error while creating a new empty file :java.io.IOException: Access is denied
Was file C:\demo123.txt created ? : false
Showing exception
Was file C:\demo123.txt created ? : false