Do I need to delete tmp files created by my java application?

一世执手 提交于 2019-12-12 12:26:54

问题


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 ");
            }

回答1:


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.



来源:https://stackoverflow.com/questions/17122580/do-i-need-to-delete-tmp-files-created-by-my-java-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!