如何使用 Java 在当前用户的主目录中创建文件? [英] how can I create a file in the current user's home directory using Java?

查看:32
本文介绍了如何使用 Java 在当前用户的主目录中创建文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hello I was just wondering how to make a custom directory below the current user's home directory. I've tried this already and it doesn't work... (Code below)

我想让它进入这个目录并在文档文件夹中创建文件夹

I want it to go to this directory and create the folder in the documents folder

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

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"目录...

First, use System.getProperty("user.home") to get the "user" directory...

String path = System.getProperty("user.home") + File.separator + "Documents";
File customDir = new File(path);

其次,使用File#mkdirs 而不是 File#mkdir 确保创建了整个路径,因为 mkdir 假设只需要创建最后一个元素

Second, use File#mkdirs instead of File#mkdir to ensure the entire path is created, as mkdir assumes that only the last element needs to be created

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

Now you can use File#exists to check if the abstract path exists and if it doesn't File#mkdirs to make ALL the parts of the path (ignoring those that do), for example...

if (customDir.exists() || customDir.mkdirs()) {
    // Path either exists or was created
} else {
    // The path could not be created for some reason
}

更新

可能需要进行的各种检查的简单分解.前面的示例只关心路径是否存在或是否可以创建.这会打破这些检查,以便您可以看到发生了什么......

A simple break down of the various checks that might need to be made. The previous example only cares if the path exists OR it can be created. This breaks those checks down so that you can see what's happening...

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 的额外文件夹;)

Note, I've added an additional folder called Your Custom Folder to the path ;)

这篇关于如何使用 Java 在当前用户的主目录中创建文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆