I have an Eclipse project with the following code that uses Apache POI.
public static void main(String[] args){
try{
XSSFWorkbook sourceWorkbook = new XSSFWorkbook("input.xlsx");
XSSFSheet sheet = sourceWorkbook.getSheetAt(0);
// do stuff
sourceWorkbook.close();
} catch (IOException e){
e.printStackTrace();
}
}
When I launch it from Eclipse, it works properly. Since I created the executable jar, when I use it, the Excel input file passes from 9 to 1 kB and it won't open anymore.
[EDIT: since I was asked:
- the file is only read, I never write it.
- the version of apache POI is 3.15 ]
How can I fix it?
CodePudding user response:
You could try the following option:
- create a
FileInputStream
to the workbook path - do that in a
try
-with-resources statement - close the workbook inside the
try
block
Maybe like this:
public static void main(String[] args) {
String wbPath = "input.xlsx";
// use an auto-closable resource stream
try (FileInputStream fis = new FileInputStream(wbPath)) {
// then use that in order to open the workbook
Workbook workbook = new XSSFWorkbook(fis);
// then open the sheet
Sheet sheet = workbook.getSheetAt(0);
// and do stuff…
// Having done stuff, close the workbook explicitly
workbook.close();
// and let the try with resources close the input stream
} catch (FileNotFoundException e) {
// do proper exception handling here
throw new RuntimeException("file " wbPath " seems not to exist");
} catch (IOException e) {
// do proper exception handling here, too
throw new RuntimeException("error during read or write operation");
}
}
The RuntimeException
s are just for making the code work and not just printing a stack trace there. As the comments say, you might want to do something better in the catch
blocks.
As an alternative to new XSSFWorkbook(fis)
you could use the WorkbookFactory
in order to create(fis)
.