java项目中获取文件路径的几种方法

本文详细介绍了四种在Java中获取项目路径的方法,包括通过getResource获取类路径、利用File类的getCanonicalPath方法、使用System.getProperty读取当前工作目录以及通过ClassLoader获取src目录下文件路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1  // 第一种:
 2  File f = new File(this.getClass().getResource("/").getPath());
 3  // 结果: /Users/admin/Documents/IdeaProjects/Demo/out/production/Demo
 4  System.out.println(f);
 5 
 6  f = new File(this.getClass().getResource("").getPath());
 7  // 多返回了包名
 8  // 结果: /Users/admin/Documents/IdeaProjects/Demo/out/production/Demo/com/company
 9  System.out.println(f);
10 
11 
12  // 第二种:获取项目名
13  File directory = new File("");
14  String courseFile = null;
15  try {
16     courseFile = directory.getCanonicalPath();
17  } catch (IOException e) {
18     e.printStackTrace();
19  }
20  // 结果: /Users/admin/Documents/IdeaProjects/Demo
21  System.out.println(courseFile);
22 
23  // 第三种:获取项目名
24  // 结果: /Users/admin/Documents/IdeaProjects/Demo
25  System.out.println(System.getProperty("user.dir"));
26 
27  // 第四种:获取项目中src目录下的一级文件路径
28  URL path = this.getClass().getClassLoader().getResource("test.txt");
29  System.out.println(path.getPath());

 

转载于:https://www.cnblogs.com/wjf0/p/9066329.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值