springboot 项目中读取资源文件内容 如图片、文档文件

1 问题描述:在 springboot 项目中有时候会需要读取一些资源文件,例如 office的 docx 文档或者 png、jpg的图片。在多模块项目中资源文件需要放到启动项目的 Resources 文件夹

示例代码如下:

InputStream pngInStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("img.png");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int n;
        while ((n = pngInStream.read(buffer)) != -1) {
            out.write(buffer,0,n);
        }
        System.out.println(out.toByteArray());

可以将 Resources 目录下的 img.png 图片读取出来,存放到 out 对象中。

在应用中涉及到 io 操作时最好将数据转换成 io 流,提高运算速度,可以到内存中运算。ByteArrayOutputStream, ByteArrayInputStream

不要使用 InputStream.avaiable() 方法,在不同系统中读到的数据可能不一样

猜你喜欢

转载自www.cnblogs.com/zhaopengcheng/p/10539894.html