首先,使用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的路径中的附加文件夹;)


版权声明:本文为weixin_34505326原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_34505326/article/details/114514811