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;
    }

从流中获取

版权声明:本文为博主作者:白大锅原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/weixin_45735355/article/details/134160438

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2024年4月1日
下一篇 2024年4月1日

相关推荐