I am using a Java program to read and write an existing .xlsx file(same file) but the file is getting corrupted, and the file size becomes zero bytes which is causing "org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long)”.
One more thing is - this is not happening consistently. The program is reading and writing to file properly most of the time but occurring once out of 10-15 runs. It would be helpful if anyone has a solution to this. BTW, am using Apache POI 3.13.
Read File Program:
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;
Write File Program :
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();
}
}
Error Trace:
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)