Apache POI在读取XLSX工作簿时抛出IOException

时间:2012-12-28 13:34:06

标签: java apache-poi inputstream ioexception xlsx

我正在尝试运行以下代码并获得IOException

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大师都可以帮助找出我要去哪里吗?提前谢谢。

3 个答案:

答案 0 :(得分:5)

问题很简单:

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

在将输出流传递给构造函数之前,您正在关闭它,并且无法读取它。

只需删除此处的is.close()即可解决问题,因为它将在最后的finally语句中进行清理。

答案 1 :(得分:2)

您正在关闭流is.close();

然后使用它,在使用它之前不要关闭它。

答案 2 :(得分:1)

正如其他人所指出的那样,你正在关闭正在破坏事物的InputStream

但是,你真的不应该首先使用InputStream! POI uses less memory when given the File object directly而不是通过InputStream。

我建议您阅读POI FAQ on File vs InputStream,然后将代码更改为:

OPCPackage pkg = OPCPackage.open(new File("/mydata/myworkbook.xlsx"));
Workbook wb = new XSSFWorkbook(pkg);