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.sql.SQLTimeoutException异常的正确解决方法(亲测有效!)
在我们编写程序的时候,有时候要进行复杂的查询时,就会出现执行sql时间过长,引起页面执行不了并提示执行脚本超时,这就是我们遇到超时异常,这篇文章主要给大家介绍了关于java.sql.SQLTimeoutException异常的正确解决方法,需要的朋友可以参考下2024-02-02


最新评论