Java - 从resources中读取文件

项目中有时候会存放一些文件到resources中,需要用的时候进行获取。

import org.springframework.core.io.ClassPathResource;

/**

* 获取resource下的文件流

* @param filePath

* @return

*/

public static InputStream getResourceInputStream(String filePath) {

    try {

        ClassPathResource classPathResource = new ClassPathResource(filePath);

        // classPathResource.getFile() jar包的时候也不可用,会遇到URI is not hierarchical问题

        return classPathResource.getInputStream();

    } catch (Exception e) {

        log.error("获取Resource中的文件异常 {} {}", filePath, e);

    }

}

例:

我们在resources中新建了一个test文件夹,在这个文件中放了一个test.txt文件。

那么我们通过下面的方法就能获取到文件流:getResourceInputStream("test/test.txt")

不需要在maven中做额外的配置。

使用jar包的时候,不能使用getFile方法,会碰到URI is not hierarchical问题。
可以用getInputStream方法,获取到stream,而后进行根据自身的需求进行转化

参考资料:SpringBoot 获取 resource 目录下的文件

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容