Java – how do I use garbage collection to delete files?

Hi, I use a lot of temporary files in Java. My problem is that they won't be deleted

There is no need to implement my own temporary file management processing (it's not very difficult, I grant you, but I'm lazy and have a lot of things to do. It's better if I can save and reinvent the wheel). Is there any way to ensure that temporary files will be deleted in a fairly regular way on disk

1 – use file TMP = file Createtempfile(), make sure I can say TMP Deleteonexit() but if something is running in the service, the only way it exits is if it crashes (which rarely happens), or when the system crashes (such as when the drive is completely full of temporary files and overturns the cluster... Oops!)

Ideally, the created instance is collected by the garbage collector at some time, and because there is a lot of idle time in the application, it would be too fancy if the GC could complete its cleanup and actually delete the files Disks can also be used to dereference instances from memory

The only way I see now is to overload the file class and add a finalized method... If I do, I can choose my own temporary file manager!

To make a long story short, can I use the garbage collector to clean up system resources (i.e. files)?

Thank you for your answers I accepted christoffer because it was the simplest implementation and the last thing I did

I think after so many years of cleaning up, I forgot the basic housekeeping, even though I made a lot of efforts in the good days of C

Solution

Of course you can The question is whether you really want to:)

I actually encountered this problem in the wild; As you have noticed, it is useless to use deleteonexit() to clear temporary files when running services rather than applications I found that the most stable solution is to refactor the program flow to create temporary files on a per task basis and explicitly delete them when they are no longer needed

If you do this in any other way, that is, if the program cannot determine whether temporary files should be retained or discarded during execution, there may be a design problem In some manager tools, wrapping files only postpones the "real" solution;)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>