Java 创建文件 获取用户目录,工程目录

今天用java写一个创建文件的demo,结果一直报错,基础不好,记录一下。

package star.sky.another;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

/**
 * @Description
 * @Author Another
 * @Date 2020/2/24 7:59
 **/
public class Test {
    public static void main(String[] args) {
        File file = new File("C:\\temp\\another.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(file.getAbsolutePath());
    }
}

报错 java.io.IOExpception: 系统找不到指定的路径

java.io.IOException

我一开始以为是文件的分隔符写错了,改为File file = new File("C:/temp/another.text"); 之后,还是不行,然后我又改为了File file = new File("C:" + File.separator + "temp" + File.separator + "another.txt"); 还是不行,看来不是分隔符的问题,然后又换到了D盘符,结果就可以了,我想不明白,难道C盘符还限制用户不能用代码创建文件?可是好多应用都是默认C盘安装,怎么可能会是有所限制。

然后我才发现,是创建文件的时候,不能够"级联"创建文件,可能用级联这个词不太恰当,就是文件只能在目录已经存在的情况下才能进行创建,当然也可以先创建目录,然后再创建文件。

public class Test {
    public static void main(String[] args) {
        String path = "C:" + File.separator + "temp" + File.separator;
        File pathFile = new File(path);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        File file = new File(path + "another.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(file.getAbsolutePath());
    }
}

然后获取用户目录使用System.getProperty("user.home") ,当然,如果需要更多系统属性或者目录相关信息,可以列出查看都有哪些信息,找到需要的即可。

public class Test {
    public static void main(String[] args) {
        Properties properties = System.getProperties();
        properties.forEach((key, value) -> {
            System.out.println(key + "---" + value);
        });
        String userHome = System.getProperty("user.home");// userHome 是 C:\Users\用户名
        String userDir = System.getProperty("user.dir");// userDir 工程项目目录
        System.out.println(userHome);
        System.out.println(userDir);
        System.out.println("-------------------------");
        Map<String, String> map = System.getenv();
        map.forEach((key, value) -> {
            System.out.println(key + "---" + value);
        });
        String userName = System.getenv("USERNAME");// userName 用户名称
        System.out.println(userName);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值