如何使用 Java 在当前用户的主目录中创建文件?



您好,我只是想知道如何在当前用户的主目录下创建自定义目录。我已经试过了,但它不起作用...(下面的代码)

我希望它转到此目录并在文档文件夹中创建文件夹

c:/users/"user"/documents/SimpleHTML/

File SimpleHTML = new File("C:/Users/"user"/Documents"); {
//  if the directory does not exist, create it
if (!SimpleHTML.exists()) {
    System.out.println("createing direcotry: " + SimpleHTML);
    boolean result = SimpleHTML.mkdir();
        if(result) {
            System.out.println("Direcotry created!");
        }
}
new simplehtmlEditor() {
    //Calling to Open the Editor
};
}

首先,使用 System.getProperty("user.home") 获取 "user" 目录...

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 的附加文件夹添加到路径;)

请注意,您也可以使用 Commons-IO

File userDirectory = org.apache.commons.io.FileUtils.getUserDirectory();

最新更新