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

从流中获取

猜你喜欢

转载自blog.csdn.net/weixin_45735355/article/details/134160438