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

如何在当前用户&x27;中创建文件;使用Java的主目录?,java,directory,Java,Directory,您好,我只是想知道如何在当前用户的主目录下创建自定义目录。我已经试过了,但不起作用。。。(代码如下) 我希望它转到这个目录,并在documents文件夹中创建文件夹 c:/users/“user”/documents/SimpleHTML/ File SimpleHTML = new File("C:/Users/"user"/Documents"); { // if the directory does not exist, create it if (!SimpleHTML.exists

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

我希望它转到这个目录,并在documents文件夹中创建文件夹

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);
其次,使用而不是确保创建整个路径,因为
mkdir
假定只需要创建最后一个元素

现在,您可以使用检查抽象路径是否存在,以及是否不存在,以使路径的所有部分(忽略那些存在的部分),例如

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();

这可能是我从中获得代码的地方,但它对我不起作用……您有语法错误,
File SimpleHTML=new File(“C:/Users/”+user+“/Documents”);{
,将这些plus添加到concat 2 stringI我刚刚更改了代码,但它仍然没有创建文件夹,甚至结果println也没有打印到控制台。@Zeak,如果要创建文件夹SimpleHTML,那么它应该是File SimpleHTML=new File(“C:/Users/”+user+“/Documents/SimpleHTML”);我只是测试了一下,然后放了一个简单的System.out.println来看看会发生什么,在控制台上它说它工作了,但我看不到文档中的文件夹。你能检查一下文件的状态吗?#exists是否返回真值,就像我想象的那样,文档已经存在了……我会稍微更新一下这个问题,对不起,我不知道你的意思,我明白你的意思e你知道我对Java很陌生。是的,谢谢你,MadProgramer!它是在我想要的地方创建的,你帮了我很多,现在我可以继续制作我的程序:)而且现在我知道如何做Directory做了一个很好的改变(得到一些有用的东西);)