0

我创建了一个扩展 BufferedInputStream 的“ResetOnCloseInputStream”,因为我将它传递给 WorkbookFactory.create(InputStream) 并在阅读工作簿后关闭流,而我需要再次使用流。ResetOnInputStream 看起来像这样 -

public class ResetOnCloseInputStream extends BufferedInputStream {

private final InputStream decorated;

public ResetOnCloseInputStream(InputStream anInputStream) {
    super(anInputStream);
    if (!anInputStream.markSupported()) {
        throw new IllegalArgumentException("marking not supported");
    }

    anInputStream.mark( 1 << 24); // magic constant: BEWARE
    decorated = anInputStream;
}

@Override
public void close() throws IOException {
    decorated.reset();
}
public void realClose() throws IOException {
    decorated.close();
}

@Override
public int read() throws IOException {
    return decorated.read();
}
}

但是当它传递给

workbook = WorkbookFactory.create(stream);

我得到这个错误-

Caused by: java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:145)
at java.io.BufferedInputStream.read(BufferedInputStream.java:308)
4

1 回答 1

0

我没有得到你给定课程的例外情况ResetOnCloseInputStream

    File inputFile = new File("C:/Test/Test.xls");
    FileInputStream fileInput;
    try {
        fileInput = new FileInputStream(inputFile);
        BufferedInputStream bufferInput = new ResetOnCloseInputStream(new BufferedInputStream(fileInput));
        Workbook workbook = WorkbookFactory.create(bufferInput);
        Sheet s1 = workbook.getSheetAt(0);
        System.out.println(s1.getSheetName()); //Sheet1
    } catch (IOException | EncryptedDocumentException | InvalidFormatException e) {
        e.printStackTrace();
    }

我猜问题可能出在stream您创建的 InputStream 上,它可能在传递给WorkbookFactory.create(bufferInput).

于 2018-06-29T17:42:43.067 回答