首先,使用
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在路径中添加了另一个文件夹;)



