簡體   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