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 を使用するべきではありません。POI は、InputStream を経由するのではなく、File オブジェクトを直接指定すると、メモリの使用量が少なくなります。

File vs InputStreamの POI FAQ を読んでから、コードを次のように変更することをお勧めします。

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