关于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);
}

 

posted @ 2021-12-21 10:33  风光小磊  阅读(571)  评论(0编辑  收藏  举报