栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

首先,使用

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/617079.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号