问题
I want to create a file if and only if that file does not exist.
As an example file location is referring to "C:\user\Desktop\dir1\dir2\filename.txt"
if (!file.exists()) {
try {
file.createNewFile();
} catch(IOException ioe) {
ioe.printStackTrace();
return;
}
}
Unfortunately the above code is failing, as the dir1
and dir2
does not exist.
For my case
- Sometime the dir1 and dir2 may exist and sometime they may not exist.
- I do not want to overwrite the contents of these intermediate directories if they already exists,
How to check this cleanly?
I was thinking to add the following check to handle this condition:
if (!file.getParentFile().getParentFile().exists()) {
file.getParentFile().getParentFile().mkdirs();
}
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch(IOException ioe) {
ioe.printStackTrace();
return;
}
}
Or there is a clearer solution than this?
回答1:
you can do something of this sort:
file.getParentFile().mkdirs();
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
Update
if (file.getParentFile().exists || file.getParentFile().mkdirs()){
try
{
file.createNewFile();
}
catch(IOException ioe)
{
ioe.printStackTrace();
return;
}
} else {
/** could not create directory and|or all|some nonexistent parent directories **/
}
回答2:
Beware that File.exists()
checks for the existence of a file or directory.
Instead of:
if(!file.exists()) {
try {
file.createNewFile();
} catch(IOException ioe) {
ioe.printStackTrace();
return;
}
}
You should explicitly check if the file is a file as there may be a directory of the same name:
if(!file.isFile()) {
try {
file.createNewFile();
} catch(IOException ioe) {
ioe.printStackTrace();
return;
}
}
Similarly, you should check that the parent file is a directory:
if (!file.getParentFile().getParentFile().isDirectory()) { ... }
来源:https://stackoverflow.com/questions/21708229/creating-file-and-intermediate-directories-if-does-not-exist