获取项目路径下的文件信息

目标文件放在项目的resources文件夹下,文件名叫 1234.txt(文件名需要用数字或字母,用汉字会读取不到):

项目install之后,可以看到文件会到target文件夹下:

方法一:

String filePath = "/1234.txt";
InputStream inputStream = FileUtil.class.getResourceAsStream(filePath);

方法二:

String filePath = "/1234.txt";
String path = FileUtil.class.getResource(filePath).getPath();
InputStream fileInputStream = new FileInputStream(path);

方法三:这种方式文件路径path初始不带 / 杠

String filePath = "1234.txt";
InputStream inputStream = FileUtil.class.getClassLoader().
getResourceAsStream(filePath);

方法四: 这种方式文件路径path初始不带 / 杠

String filePath = "1234.txt";       
String path = Thread.currentThread().getContextClassLoader().
getResource(filePath).getPath();
InputStream fileInputStream = new FileInputStream(path);

方法五:System.getProperty 先拿项目根路径,再拼接target/classes 以及文件路径

String filePath = "/1234.txt";
String relativelyPath = System.getProperty("user.dir");
InputStream fileInputStream = new FileInputStream(relativelyPath + "/target/classes/" + filePath);

方法六: Paths.get("").toAbsolutePath() 先拿项目根路径,再拼接target/classes 以及文件路径

String filePath = "/1234.txt"; 
Path path = Paths.get("").toAbsolutePath();      
InputStream fileInputStream = new FileInputStream(path + "/target/classes/" + filePath);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值