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:
How can I fix it?
You could try the following option:
FileInputStream
to the workbook pathtry
-with-resources statementtry
blockMaybe 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)
.