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

"这篇博客介绍了如何使用Java在当前用户的文档目录下创建自定义文件夹。关键点在于使用`System.getProperty("user.home")`获取用户目录,并用`File#mkdirs()`确保路径的完整创建。如果路径不存在,则会尝试创建,通过`exists()`和`mkdirs()`方法检查并创建目录。"
摘要由CSDN通过智能技术生成

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/

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

};

}

解决方案

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

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

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

}

Updated

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

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值