Apache poi's documentation (version 3.17) says
void close()
throws java.io.IOException
Close the underlying input resource (File or Stream), from which the Workbook was read.
My code creates a workbook from a template file, does something with it and writes it to a new file. The template file should be left unchanged. But when I call the close() method, the file is changed in the same way as the output file.
Can someone explain this? Is there something like a built-in write() call in the close() method? Is this a bug or a feature?
My solution so far is to just leave away the close() call, but it feels incomplete somehow.
String inPath = "/home/elmicha/test/template.xlsx";
String outPath = "/home/elmicha/test/out.xlsx";
try {
Workbook xlsxFile = WorkbookFactory.create(new File(inPath));
xlsxFile.getSheetAt(0).createRow(0).createCell(0).setCellValue("test");
try (FileOutputStream pOuts = new FileOutputStream(outPath)) {
xlsxFile.write(pOuts);
xlsxFile.close();
}
} catch (IOException | InvalidFormatException | EncryptedDocumentException ex) {
//...
}
That's quite unusual. I don't see why the template file would be written to. It certainly wasn't my experience. You can try:
FileInputStream instead of File to make it impossible to write to the template file.Workbook.Here's an example:
String inPath = "/home/elmicha/test/template.xlsx";
String outPath = "/home/elmicha/test/out.xlsx";
try (Workbook xlsxFile = WorkbookFactory.create(new FileInputStream(inPath))) {
xlsxFile.getSheetAt(0).createRow(0).createCell(0).setCellValue("test");
try (FileOutputStream pOuts = new FileOutputStream(outPath)) {
xlsxFile.write(pOuts);
}
} catch (IOException | InvalidFormatException | EncryptedDocumentException ex) {
//...
}
Or perhaps:
String inPath = "/home/elmicha/test/template.xlsx";
String outPath = "/home/elmicha/test/out.xlsx";
try (Workbook xlsxFile = WorkbookFactory.create(new FileInputStream(inPath));
FileOutputStream pOuts = new FileOutputStream(outPath)) {
xlsxFile.getSheetAt(0).createRow(0).createCell(0).setCellValue("test");
xlsxFile.write(pOuts);
} catch (IOException | InvalidFormatException | EncryptedDocumentException ex) {
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With