Using Java.io.file to create a file (folder) is the most basic knowledge of Java.
The JDK API describes:
The snippet code will look more clearly:
File file1 =NewFile ("F:/AAA/BBB/CCC"); if(File1.mkdirs ()) {System.out.println ("Multi-tier folder creation succeeded!" After the creation of the file directory is: "+ file1.getpath () +", the parent file is: "+file1.getparent ()); } File file2=NewFile ("f:/aaa/bbb/ccc/ddd"); if(File2.mkdir ()) {System.out.println ("Single folder DDD created successfully!" After the creation of the file directory is: "+ file2.getpath () +", the parent file is: "+file2.getparent ()); } File file3=NewFile ("f:/aaa/bbb/ccc/ddd", "Mytest.txt"); Try { if(File3.createnewfile ()) {System.out.println ("Multi-level folder file creation success!" The file created is: "+ file3.getabsolutepath () +", the parent file is: "+file3.getparent ()); } } Catch(IOException e) {e.printstacktrace (); }
Output:
This makes it clear thatmkdir () creates a single folder to ensure that its parent folder exists.
Mkdirs () creates multiple folders and does not need to ensure that its parent folder exists.
Export the file to a folder to ensure that the destination folder exists.
"Bonus" Recursive delete entire folder (file) method:
/*** Delete all folders and files under a folder * *@paramDelpath *@throwsFileNotFoundExceptionIOException *@returnBoolean*/ Public Static BooleanDeleteFile (String Delpath)throwsException {File file=NewFile (Delpath); if(File.isdirectory ()) {string[] filelist=file.list (); for(String delfile:filelist) {File delfile=NewFile (Delpath + file.separator +delfile); if(Delfile.isdirectory ()) {DeleteFile (Delpath+ File.separator +delfile); } ElseSystem.out.println ("Deleting files:" + delfile.getpath () + ", Delete succeeded:" +Delfile.delete ()); } System.out.println ("Removing Empty folders:" + file.getpath () + ", Delete succeeded:" +File.delete ()); } ElseSystem.out.println ("Deleting files:" + file.getpath () + ", Delete succeeded:" +File.delete ()); return true; }
Java Foundation "12" Java.io.file file (folder) creation and deletion