关于jar包和war读取静态文件

在war包中static中的静态文件,打成jar包后却读取不到,这是为什么呢,让我门看下两种读取的区别

一。war包中都取静态模板文件

public static void download(String filename, HttpServletResponse res) throws IOException {
       // 发送给客户端的数据
       OutputStream outputStream = res.getOutputStream();
       byte[] buff = new byte[1024];
       BufferedInputStream bis = null;
// 获取全路径 String path
= Thread.currentThread().getContextClassLoader().getResource("").getPath()+"templateFile"; String filePath =""; if(ExcelUtil.isOSLinux()) { filePath = path +"/"+filename; }else { filePath = path +"\\"+filename; } // 读取filename bis = new BufferedInputStream(new FileInputStream(new File(filePath))); int i = bis.read(buff); while (i != -1) { outputStream.write(buff, 0, buff.length); outputStream.flush(); i = bis.read(buff); } bis.close(); outputStream.close(); }

问题来了,上图的获取方式中有一个共同点:都是根据文件地址来获取文件对象。该文件地址都是编译之后的文件目录,在war包中可以根据该地址获取文件,但是,当打包成JAR包时,无法通过该地址查找到文件对象,那么在JAR包中,如何读取静态文件呢?

二。jar包获取静态模板文件

公共类:

public static boolean isOSLinux() {
       Properties prop = System.getProperties();

       String os = prop.getProperty("os.name");
       if (os != null && os.toLowerCase().indexOf("linux") > -1) {
           return true;
       } else {
           return false;
       }
   }

/**
 * 根据文件名获取文件路径
 * @param filename
 * @throws IOException
 */
public static String getXSSFWorkbookByFilename(String filename) throws IOException {
    String filePath ="";
    if(ExcelUtil.isOSLinux()) {
        filePath = "templateFile/"+filename;
    }else {
        filePath = "templateFile\\"+filename;
    }
    return filePath;
}

采用流的方式读取文件:

public void exportQuesAssessorWriteRs(TsQuesAssessor tqa, OutputStream os) throws Exception {
    // 查询导出数据
    List<OpinionAboutValue> datas = tsQuesAssessorMapper.getQuesAssessorWriteList(tqa);
    OpinionAboutValueTemplate quesLimit = opinionAboutValueGradeMapper.getQuesLimit(tqa);
    // 采用流的方式读取模板文件
    String path = FileUtil.getXSSFWorkbookByFilename(tempLateFilename);
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
    //读取excel模板
    XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
    Sheet sheet = xssfWorkbook.getSheetAt(0);
    Cell cell = sheet.getRow(1).getCell(1);
    cell.setCellValue(builder.toString());
    createExceportDatas(sheet, datas);
    xssfWorkbook.write(os);
}

 


__EOF__

  • 本文作者: lei.z
  • 本文链接: https://www.cnblogs.com/lei-z/p/15714208.html
  • 关于博主: 评论和私信会在第一时间回复。或者直接私信我。
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
  • 声援博主: 如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。
  • posted @   风光小磊  阅读(609)  评论(0编辑  收藏  举报
    编辑推荐:
    · PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
    · C++代码改造为UTF-8编码问题的总结
    · DeepSeek 解答了困扰我五年的技术问题
    · 为什么说在企业级应用开发中,后端往往是效率杀手?
    · 用 C# 插值字符串处理器写一个 sscanf
    阅读排行:
    · 为DeepSeek添加本地知识库
    · 精选4款基于.NET开源、功能强大的通讯调试工具
    · DeepSeek智能编程
    · [翻译] 为什么 Tracebit 用 C# 开发
    · 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
    点击右上角即可分享
    微信分享提示