解决springboot读取jar包中文件的问题

前言

我们这边有一个需求如下:

  • 有一个模板文件,有占位符,在添加产品的时候,将占位符中内容替换成相应的产品信息并生成文件。
    在项目中使用的是springboot,在本地读取文件因为不是以jar包的方式访问,所以可以读取到文件内容,而在服务器上以jar的形式读取,所以读取的文件内容为空。
    先贴上代码
private static String readScript(String filePath){
    File file=new File(filePath);
    Long fileLength=file.length();
    byte[] fileContext=new byte[fileLength.intValue()];
    try {
        FileInputStream in=new FileInputStream(filePath);
        in.read(fileContext);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new String(fileContext);
}

这样读到文件路径为:

file:/home/build/admin/rampage-admin-web-0.1.0-SNAPSHOT-exec.jar!/BOOT-INF/classes!/templates/script.ftl

但是文件内容为空,并没有报错异常信息。后来百度后改为

private static String readScript(File file){
    Long fileLength=file.length();
    byte[] fileContext=new byte[fileLength.intValue()];
    try {
        FileInputStream in=new FileInputStream(file);
        in.read(fileContext);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new String(fileContext);
}

参数File 的值如下:

InputStream stream = getClass().getClassLoader().getResourceAsStream("templates/script.ftl");
File targetFile = new File("script.ftl");
FileUtils.copyInputStreamToFile(stream, targetFile);

此处targetFile即为参数

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

推荐阅读更多精彩内容