2012-12-28 99 views
0

我試圖讓下面的代碼運行,並正在一個IOException的Apache POI拋出IOException異常時閱讀XLSX工作簿

String cellText = null; 
InputStream is = null; 
try { 
    // Find /mydata/myworkbook.xlsx 
    is = new FileInputStream("/mydata/myworkbook.xlsx"); 
    is.close(); 

    System.out.println("Found the file!"); 

    // Read it in as a workbook and then obtain the "widgets" sheet. 
    Workbook wb = new XSSFWorkbook(is); 
    Sheet sheet = wb.getSheet("widgets"); 

    System.out.println("Obtained the widgets sheet!"); 

    // Grab the 2nd row in the sheet (that contains the data we want). 
    Row row = sheet.getRow(1); 

    // Grab the 7th cell/col in the row (containing the Plot 500 English Description). 
    Cell cell = row.getCell(6); 
    cellText = cell.getStringCellValue(); 

    System.out.println("Cell text is: " + cellText); 
} catch(Throwable throwable) { 
    System.err.println(throwable.getMessage()); 
} finally { 
    if(is != null) { 
     try { 
      is.close(); 
     } catch(IOException ioexc) { 
      ioexc.printStackTrace(); 
     } 
    } 
} 

在Eclipse中運行這個輸出:

Found the file! 
Stream Closed 
java.io.IOException: Stream Closed 
    at java.io.FileInputStream.readBytes(Native Method) 
    at java.io.FileInputStream.read(FileInputStream.java:236) 
    at java.io.FilterInputStream.read(FilterInputStream.java:133) 
    at java.io.PushbackInputStream.read(PushbackInputStream.java:186) 
    at java.util.zip.ZipInputStream.readFully(ZipInputStream.java:414) 
    at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:247) 
    at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:91) 
    at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource.<init>(ZipInputStreamZipEntrySource.java:51) 
    at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:83) 
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:267) 
    at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39) 
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:204) 
    at me.myorg.MyAppRunner.run(MyAppRunner.java:39) 
    at me.myorg.MyAppRunner.main(MyAppRunner.java:25) 

異常來自行:

Workbook wb = new XSSFWorkbook(is); 

根據XSSFWorkbook Java Docs這是一個XSSFWorkbook對象的有效構造函數,我沒有看到任何「跳出來」的對象,表示我錯誤地使用了我的InputStream。任何POI大師能幫我找出我要去哪裏?提前致謝。

回答

5

的問題很簡單:

is = new FileInputStream("/mydata/myworkbook.xlsx"); 
is.close(); 

你將它傳遞給構造函數之前關閉您的輸出流,它不能被讀取。

只需在此處刪除is.close()即可解決問題,因爲它將在finally語句中清除。

+0

Uggghhhhhhhhh ....需要咖啡(TGIF)。感謝和+1 – IAmYourFaja

2

你關閉流is.close();

,然後用它,不要關閉它,直到你使用它。

+0

DERP!是的,我需要散步,抓一些咖啡。謝謝,並且+1 – IAmYourFaja

相關問題