繁体   English   中英

Excel 启动可执行文件后文件损坏 jar

[英]Excel file gets corrupted after launching an executable jar

我有一个 Eclipse 项目,其中包含以下使用 Apache POI 的代码。

public static void main(String[] args){
    try{
        XSSFWorkbook sourceWorkbook = new XSSFWorkbook("input.xlsx");
        XSSFSheet sheet = sourceWorkbook.getSheetAt(0);
        // do stuff
        sourceWorkbook.close();         
    } catch (IOException e){
        e.printStackTrace();
    }
}

当我从 Eclipse 启动它时,它工作正常。 由于我创建了可执行文件 jar,当我使用它时,Excel 输入文件从 9 增加到 1 kB,并且不再打开。

[编辑:因为有人问我:

  • 该文件仅供读取,我从不写入。
  • apache POI 的版本是 3.15 ]

我该如何解决?

您可以尝试以下选项:

  • 创建一个FileInputStream到工作簿路径
  • try -with-resources 语句中执行此操作
  • 关闭try块内的工作簿

也许像这样:

public static void main(String[] args) {
    String wbPath = "input.xlsx";
    // use an auto-closable resource stream 
    try (FileInputStream fis = new FileInputStream(wbPath)) {
        // then use that in order to open the workbook
        Workbook workbook = new XSSFWorkbook(fis);
        // then open the sheet
        Sheet sheet = workbook.getSheetAt(0);
        
        // and do stuff…
        
        // Having done stuff, close the workbook explicitly
        workbook.close();
        // and let the try with resources close the input stream
    } catch (FileNotFoundException e) {
        // do proper exception handling here
        throw new RuntimeException("file " + wbPath + " seems not to exist");
    } catch (IOException e) {
        // do proper exception handling here, too
        throw new RuntimeException("error during read or write operation");
    }
}

RuntimeException仅用于使代码正常工作,而不仅仅是在那里打印堆栈跟踪。 正如评论所说,您可能想在catch块中做一些更好的事情。

作为new XSSFWorkbook(fis)的替代方案,您可以使用WorkbookFactorycreate(fis)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM