0

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.

  • This question is similar to yours. https://stackoverflow.com/questions/26541513/why-is-it-good-to-close-an-inputstream – moh ro Jun 09 '20 at 05:31
  • You need to close it *before* deleting the file. Otherwise the deletion may not work. But if you're going to load it all into memory, why not use a `ByteArrayOutputStream` instead? – user207421 Jun 09 '20 at 06:50

2 Answers2

0

From java 7, they introduce try with resource (you can see in oracle document). It can help to reduce closing stream manually.

SoT
  • 898
  • 1
  • 15
  • 36
0

Closing the resource is always preferable to avoid any leak of data. In Java-7 we have the try with resource feature you can use that. try-with-resources – allows us to declare resources to be used in a try block with the assurance that the resources will be closed when after the execution of that block. You can find more about the same here
https://mkyong.com/java/try-with-resources-example-in-jdk-7/ or
https://www.baeldung.com/java-try-with-resources

SSK
  • 3,444
  • 6
  • 32
  • 59