获取项目路径,项目下的文件路径的几种方式

1.获取当前类的工程路径

        创建file 来获取路径

public static void main(String[] args) {
        File file = new File("");
        String rootPath = null;
        try {
            rootPath = file.getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 当前类的工程路径
        System.out.println(rootPath);
}

2. 类的文件路径

        加 斜杠 '/' 获取项目指构建后的classes路径

public static void main(String[] args) {
        // 获取指定类的绝对路径
        File file = new File(Autowired.class.getResource("").getPath());
        System.out.println(file.getPath());
        
        // 加 斜杠 '/' 获取项目指构建后的classes路径
        File targetFile = new File(Autowired.class.getResource("/").getPath());
        System.out.println(targetFile.getPath());
}

3.获取resources目录下文件的路径

       个人猜测 根据类的位置来获取地址,归根到底还是创建file的原因,未研究

public static void main(String[] args) {

        // 获取项目resources的文件路径  \ 分割层级
        File file = new File(Autowired.class.getResource("/"+"resources下的文件地址").getPath());
        System.out.println(file.getPath());

        // 获取项目resources的文件路径 / 分割层级
        final String path = Autowired.class.getClassLoader().getResource("resources下的文件地址").getPath();
        System.out.println(path);

}

注意:以上经过测试均可操作,

如没有引用Autowired,可以替换成String等存在的类,均可

                                                                                                                                --- 努力吧骚年

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值