栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

读取工程文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

读取工程文件

 读取resources目录下的excel文件:

// @Component 和 @PostConstruct 配合,项目启动时执行。
@Component 
public class AppStartConfig {

    protected static final Logger logger = LoggerFactory.getLogger(AppStartConfig.class);

    @PostConstruct
    public void readStaticResources() throws IOException {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath:\data\static\*.xlsx");
        logger.info("resources:{}", (Object) resources);
        String path = "C:\Users\Name.last\Desktop";
        for (Resource res : resources) {
            logger.info("开始处理文件:{}", res);
            byte[] data = readFileToByteArray(res);
            writeByteArrayToFile(data,path,res.getFilename());
            logger.info("处理文件结束!");
        }
    }

    public byte[] readFileToByteArray(Resource resource) {
        // 文件输入流(需要关闭)
        InputStream is = null;
        try {
            is = resource.getInputStream();
            // 字节数组输出流(不需要关闭)
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024 * 2];
            int len;
            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            baos.flush();
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public void writeByteArrayToFile(byte[] data, String path, String fileName) {
        // 文件输出流(需要关闭)
        OutputStream os = null;
        try {
            os = new FileOutputStream(new File(path, fileName));
            // 字节数组输入流(不需要关闭)
            InputStream is = new ByteArrayInputStream(data);
            byte[] buf = new byte[1024 * 2];
            int len;
            while ((len = is.read(buf)) != -1) {
                os.write(buf, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/274868.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号