1. First make it clear that the Test.txt file can exist in the same directory as the test folder, and that the test file cannot exist in the same directory as the test folder.
The reasons are:
(1) Win files and folders are stored as nodes, which means that the same files and filenames cannot be in the same directory, naming conflicts.
(2) The file suffix name is also part of the filename, that is, the Test.txt file and the test file are not the same file names.
2. For the above reasons, if I want to create a test folder in D:, but D: there is a test file below, because of the naming conflict, it is impossible to create a successful.
Therefore, before the creation, the file.exists () to determine the existence of the test name of the file or folder, if the return true, is not created;
And then by File.isdirectory () to determine if this is not a folder.
1 ImportJava.io.File;2 Importjava.io.IOException;3 4 Public classMain {5 6 Public Static voidMain (string[] args) {7 8File File =NewFile ("D:\\test_file.txt");9 main.judefileexists (file);Ten OneFile dir =NewFile ("D:\\test_dir"); A main.judedirexists (dir); - } - the //determine if a file exists - Public Static voidjudefileexists (file file) { - - if(File.exists ()) { +System.out.println ("File exists"); -}Else { +SYSTEM.OUT.PRINTLN ("File not exists, create it ..."); A Try { at file.createnewfile (); -}Catch(IOException e) { - //TODO auto-generated Catch block - e.printstacktrace (); - } - } in - } to + //determine if a folder exists - Public Static voidjudedirexists (file file) { the * if(File.exists ()) { $ if(File.isdirectory ()) {Panax NotoginsengSystem.out.println ("dir exists"); -}Else { theSystem.out.println ("The same name file exists, can not create dir"); + } A}Else { theSystem.out.println ("Dir not exists, create it ..."); + File.mkdir (); - } $ $ } - -}
How does Java determine if a file or folder is in? Does not exist how to create?