我创建了一个'ResetOnCloseInputStream',它扩展了BufferedInputStream,因为我将它传递给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)
答案 0 :(得分: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();
}
我想问题可能出在您创建的InputStream stream
上,它可能在传递给WorkbookFactory.create(bufferInput)
之前已关闭。