首页 > 基础资料 博客日记
Java获取resources下文件路径
2024-05-25 07:00:05基础资料围观584次
文章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进行投诉反馈,一经查实,立即删除!
标签:
相关文章
最新发布
- springboot~3.x项目中使用集成测试
- Java测试类、工具类与JavaBean对比解析
- SpringBoot-日志
- springboot~http2的支持
- 解疑释惑 - 日志体系之 slf4j + logback 组合(一)
- Web server failed to start. Port 8080 was already in use. 端口被占用
- Springboot 项目配置多数据源
- 伙伴匹配系统(移动端 H5 网站(APP 风格)基于Spring Boot 后端 + Vue3 - 05
- 剑指offer-23、搜索⼆叉树的后序遍历序列
- 一个表示金额的数字是 100000000L,这是多少米?