当前位置:   article > 正文

Java获取resources下文件路径_jar包获取resource下的文件路径

jar包获取resource下的文件路径

方法一:使用ClassLoader.getResource()方法

String filePath = "path/to/file.txt";
URL resourceUrl = getClass().getClassLoader().getResource(filePath);
String resourcePath = resourceUrl.getPath();
  • 1
  • 2
  • 3

方法二:使用ClassLoader.getResourceAsStream()方法

String filePath = "path/to/file.txt";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filePath);
  • 1
  • 2

方法三:使用Class.getResource()方法

String filePath = "path/to/file.txt";
URL resourceUrl = getClass().getResource(filePath);
String resourcePath = resourceUrl.getPath();
  • 1
  • 2
  • 3

方法四:使用Class.getResourceAsStream()方法

String filePath = "path/to/file.txt";
InputStream inputStream = getClass().getResourceAsStream(filePath);
  • 1
  • 2

问题记录

获取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;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

此处也能获取到文件路径 仅限本地 当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;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

从流中获取

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/728251
推荐阅读
相关标签
  

闽ICP备14008679号