I am using Spring Boot to develop a method to concatenate many .pfd files into a single one and return its byte array:
public byte[] concatDocs() {
List<Doc> documents = getAllDocs();
PDFMergerUtility ut = new PDFMergerUtility();
String nameOfTemporaryFile = "temporaryFile.pdf";
File file = new File(nameOfTemporaryFile);
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
for (Doc doc : documents) {
InputStream is = new ByteArrayInputStream(doc.getFile());
ut.addSource(is);
}
ut.setDestinationStream(out);
ut.mergeDocuments(null);
byte[] fileBytes = Files.readAllBytes(file.toPath());
file.delete();
return fileBytes;
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
The code itself is working perfectly: It gets the Doc
List, creates the temporary File
along with the FileOutputStream
(from java.io
), uses the PDFMergerUtility
to unite the files and generate the byte array and finally deletes the file from the computer. My questions are:
Every code I see on the internet that works with I/O Stream always closes them in the end (with stream.close()
), but I've never found a good explaination on why they always do this...
Should I close out
before I readAllBytes
?
Should I close out
before or after I delete the File?
As I'm deleting the File, do I even need to close out
?
What if an Exception is thrown? Should I close out
on a finally
clause?
Should I out.flush()
somewhere?
Should I call System.gc();
?
Thanks in advance.