0

我正在尝试运行以下代码并得到一个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 专家都可以帮助发现我哪里出错了吗?提前致谢。

4

3 回答 3

6

问题很简单:

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

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

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

于 2012-12-28T13:36:31.400 回答
2

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

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

于 2012-12-28T13:36:10.317 回答
1

正如其他人所指出的那样,您正在关闭InputStream正在破坏的东西

但是,您真的不应该首先使用 InputStream!当直接给定 File 对象而不是通过 InputStream时,POI 使用更少的内存。

我建议您阅读有关 File vs InputStream 的 POI 常见问题解答,然后将您的代码更改为:

OPCPackage pkg = OPCPackage.open(new File("/mydata/myworkbook.xlsx"));
Workbook wb = new XSSFWorkbook(pkg);
于 2012-12-28T14:54:57.743 回答