Java获取resources下文件路径的几种方法及遇到的问题
更新时间:2023年12月14日 11:39:53 作者:白大锅
这篇文章主要给大家介绍了关于Java获取resources下文件路径的几种方法及遇到的问题,在Java开发中经常需要读取项目中resources目录下的文件或获取资源路径,需要的朋友可以参考下
方法一:使用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;
}
从流中获取
总结
到此这篇关于Java获取resources下文件路径的几种方法及遇到的问题的文章就介绍到这了,更多相关Java获取resources文件路径内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Java web入门指南之在Idea上创建Java web项目
好多书上的JavaWeb教程都是Eclipse以及MyEclipse,当然这里不论IDE的好坏,下面这篇文章主要给大家介绍了关于Java web入门指南之在Idea上创建Java web项目的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下2023-06-06
Spring Boot、Redis、RabbitMQ 在项目中的核心作用详解(代码示例)
在现代企业级应用开发中,Spring Boot、Redis 和 RabbitMQ 已经成为不可或缺的技术组件,本文将深入剖析这三者在实际项目中的作用,并通过代码示例和流程图展示它们的实际应用,感兴趣的朋友一起看看吧2025-11-11


最新评论