首页 > 基础资料 博客日记
Java获取resources下文件路径
2024-05-25 07:00:05基础资料围观533次
文章Java获取resources下文件路径分享给大家,欢迎收藏Java资料网,专注分享技术知识
方法一:使用ClassLoader.getResource()方法
String filePath = "path/to/file.txt";
URL resourceUrl = getClass().getClassLoader().getResource(filePath);
String resourcePath = resourceUrl.getPath();
方法二:使用ClassLoader.getResourceAsStream()方法
String filePath = "path/to/file.txt";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filePath);
方法三:使用Class.getResource()方法
String filePath = "path/to/file.txt";
URL resourceUrl = getClass().getResource(filePath);
String resourcePath = resourceUrl.getPath();
方法四:使用Class.getResourceAsStream()方法
String filePath = "path/to/file.txt";
InputStream inputStream = getClass().getResourceAsStream(filePath);
问题记录
获取resources目录下某文件路径并返回
public String getResourcesPath(String filePath) {
String resourcePath=null;
try {
Resource resource = new ClassPathResource(filePath);
Path path = resource.getFile().toPath();
resourcePath=path.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
return resourcePath;
}
此处也能获取到文件路径 仅限本地 当jar包时 是无法获取到该文件具体的路径的 我的解决方案如下:
public String getResourcesPath(String filePath) {
String resourcePath=null;
File file = new File(filePath);
try {
Resource resource = new ClassPathResource(filePath);
InputStream inputStream = resource.getInputStream();
FileUtils.copyInputStreamToFile(inputStream, file);
resourcePath=file.getAbsolutePath();
} catch (IOException e) {
throw new RuntimeException(e);
}
return resourcePath;
}
从流中获取
文章来源:https://blog.csdn.net/weixin_45735355/article/details/134160438
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:
相关文章
最新发布
- hot100之普通数组
- 记一次诡异的线上异常赋值排查:代码没错,结果不对
- hot100之子串
- 剑指offer-1、⼆维数组中的查找
- 从尾到头打印链表
- 秒杀/高并发解决方案+落地实现 (技术栈: SpringBoot+Mysql + Redis +RabbitMQ +MyBatis-Plus +Maven + Linux + Jmeter ) -03
- @ModelAttribute、@RequestBody、@RequestParam、@PathVariable 注解对比
- Java 样板代码库 Lombok 使用详解
- wso2~自定义event-publisher
- 数组数量数据数量大 1000万黑名单用户 一百亿基础用户 查询检索思路