read error java_使用Poi读取excel2007文件报java.io.IOException: Read error

我的代码是这样写的:

FileInputStream inf = new FileInputStream(filePath + outerExcelFileName);

Workbook workbook = null;

try {

//2003

workbook = new HSSFWorkbook(inf);

} catch( org.apache.poi.poifs.filesystem.OfficeXmlFileException e){

//2007

workbook = new XSSFWorkbook(inf);

}catch (org.apache.poi.hssf.OldExcelFormatException e) {

outLog.write("Excel文件为95版本,请另存为2003或2000格式再试
\n");

outLog.close();

result = "error";

return result;

} finally{

inf.close();

inf = null;

}

在读取excel2003文件时,还能正常使用,当读取excel2007文件时,走入catch块,就会报下面的错:

java.io.IOException: Read error at java.io.FileInputStream.readBytes(Native Method) at java.io.FileInputStream.read(Unknown Source)

......

下午看csdn一个帖子,有人说“当创建2007excel失败时,Workbook的实例对象的某些信息已经是2007的格式了”(他的代码是在try里处理2007的),于是反编译了poi的HSSFWorkbook类看了一下:

public HSSFWorkbook(InputStream s) throws IOException {

this(s, true);

}

public HSSFWorkbook(InputStream s, boolean preserveNodes) throws IOException{

this(new POIFSFileSystem(s), preserveNodes);

}

POIFSFileSystem类:

public POIFSFileSystem(InputStream stream) throws IOException {

this();

boolean success = false;

HeaderBlockReader header_block_reader;

RawDataBlockList data_blocks;

try {

header_block_reader = new HeaderBlockReader(stream);

this.bigBlockSize = header_block_reader.getBigBlockSize();

data_blocks = new RawDataBlockList(stream, this.bigBlockSize);

success = true;

} finally {

closeInputStream(stream, success);

}

......

}

private void closeInputStream(InputStream stream, boolean success){

if ((stream.markSupported()) && (!(stream instanceof ByteArrayInputStream))) {

String msg = "POIFS is closing the supplied input stream of type (" + stream.getClass().getName() + ") which supports mark/reset. " + "This will be a problem for the caller if the stream will still be used. " + "If that is the case the caller should wrap the input stream to avoid this close logic. " + "This warning is only temporary and will not be present in future versions of POI.";

_logger.log(POILogger.WARN, msg);

}

try {

stream.close();

} catch (IOException e) {

if (success) {

throw new RuntimeException(e);

}

e.printStackTrace();

}

}

原来是在里面给close了...

最后修改为在new xxxxWorkbook之前再newFileInputStream了

poi所需jar包:

dom4j-1.7-20060614.jar

log4j-1.2.13.jar poi-3.7-20101029.jar poi-ooxml-3.7-20101029.jar poi-ooxml-schemas-3.7-20101029.jar xmlbean.jar

你可能感兴趣的:(read,error,java)