首先,使用System.getProperty(“user.home”)获得 “用户” 目录…
String path = System.getProperty(“user.home”) + File.separator + “Documents”;
File customDir = new File(path);
二,使用File#mkdirs代替File#mkdir确保整个路径被创建,为mkdir假定只有最后一个元素需要创建
现在你可以使用File#exists检查抽象路径存在,如果它不File#mkdirs做出的所有部件路径(忽略那些做的),例如…
if (customDir.exists() || customDir.mkdirs()) {
// Path either exists or was created
} else {
// The path could not be created for some reason
}
更新
一个简单的突破,可能需要进行各种检查的下降。前面的例子只关心路径是否存在或者是否可以创建。这打破这些检查下来,让你可以看到发生了什么……
String path = System.getProperty(“user.home”) + File.separator + “Documents”;
path += File.separator + “Your Custom Folder”
File customDir = new File(path);
if (customDir.exists()) {
System.out.println(customDir + ” already exists”);
} else if (customDir.mkdirs()) {
System.out.println(customDir + ” was created”);
} else {
System.out.println(customDir + ” was not created”);
}
注意,我也添加了Your Custom Folder的路径中的附加文件夹;)