我正在使用 Java 程序读取和写入现有的 .xlsx 文件(同一文件),但文件已损坏,文件大小变为零字节,这导致 "org.apache.poi.EmptyFileException : 提供的文件为空(零字节长)”。
还有一件事是 - 这不是一直发生的。该程序大部分时间都在正确读取和写入文件,但在 10-15 次运行中只发生一次。如果有人对此有解决方案,那将很有帮助。顺便说一句,我正在使用 Apache POI 3.13。
读文件程序:
public String getExcelData(String sheetName, int rowNum, int colNum){
String retVal = null;
try {
FileInputStream fis = new FileInputStream("/Absolute/File/Path/Test-File.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet s = wb.getSheet(sheetName);
Row r = s.getRow(rowNum);
Cell c = r.getCell(colNum);
retVal=(c.getStringCellValue());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retVal;
写文件程序:
public void writeToExcel(String sheetName,int rowNum,int cellNum,String desc){
try {
FileInputStream fis = new FileInputStream("/Absolute/File/Path/Test-File.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet s = wb.getSheet(sheetName);
Row r = s.getRow(rowNum);
Cell c = r.createCell(cellNum);
c.setCellValue(desc);
FileOutputStream fos = new FileOutputStream("/Absolute/File/Path/Test-File.xlsx");
wb.write(fos);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
错误跟踪:
Exception in thread "main" org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long)
at org.apache.poi.util.IOUtils.peekFirst8Bytes(IOUtils.java:55)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:201)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:168)
at ExcelLibrary.getExcelData(ExcelLibrary.java:139)
at Driver.main(Driver.java:82)
最佳答案
您正在同时读取和写入同一个文件。在写入 FileOutputStream fos 之前尝试先关闭 FileInputStream fis。 或者使用临时文件写入新结果,然后将其重命名为原始结果。
顺便说一句。 close 自动执行刷新,因此不必单独调用。
关于Java - Apache POI - 读/写 .xlsx 文件 - 文件损坏并变为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34264120/