Question

I output several temporary files in my application to tmp directories but was wondering if it is best practise that I delete them on close or should I expect the host OS to handle this for me?

I am pretty new to Java, I can handle the delete but want to keep the application as multi-OS and Linux friendly as possible. I have tried to minimise file deletion if I don't need to do it.

This is the method I am using to output the tmp file:

 try {
                java.io.InputStream iss = getClass().getResourceAsStream("/nullpdf.pdf");
                byte[] data = IOUtils.toByteArray(iss);
                iss.read(data);
                iss.close();
                String tempFile = "file";
                File temp = File.createTempFile(tempFile, ".pdf");
                FileOutputStream fos = new FileOutputStream(temp);
                fos.write(data);
                fos.flush();
                fos.close();
            nopathbrain = temp.getAbsolutePath();
            System.out.println(tempFile);
            System.out.println(nopathbrain);
            } catch (IOException ex) {
                ex.printStackTrace();
                System.out.println("TEMP FILE NOT CREATED - ERROR ");
            }
Était-ce utile?

La solution

createTempFile() only creates a new file with a unique name, but does not mark it for deletion. Use deleteOnExit() on the created file to achieve that. Then, if the JVM shuts down properly, the temporary files should be deleted.

edit: Sample for creating a 'true' temporary file in java:

File temp = File.createTempFile("temporary-", ".pdf");
temp.deleteOnExit();

This will create a file in the default temporary folder with a unique random name (temporary-{randomness}.pdf) and delete it when the JVM exits.

This should be sufficient for programs with a short to medium run time (e.g. scripts, simple GUI applications) that do sth. and then exit. If the program runs longer or indefinitely (server application, a monitoring client, ...) and the JVM won't exit, this method may clog the temporary folder with files. In such a situation the temporary files should be deleted by the application, as soon as they are not needed anymore (see delete() or Files helper class in JDK7).

As Java already abstracts away OS specific file system details, both approaches are as portable as Java. To ensure interoperability have a look at the new Path abstraction for file names in Java7.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top