Moorthy
Moorthy

Reputation: 45

How to avoid delete the Temp files using java?

I have a simple code to generate the temp files and store the some values(I don't want to store the files in normal storage area) In future, I want to use that file and get the data from that file (its not a problem if the user manually delete the files). But I don't want to delete the files automatically. when read this link, I get some information, generally temp files not deleted when you explicitly call deleteOnExit() but when my JVM finish the work temp file deleted automatically.

//create a temp file
File temp = File.createTempFile("demo_", ".txt");
String path = temp.getParent();

//count the file which names starts with "demo"
File f = new File(path);
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
    return name.startsWith("demo") && name.endsWith(".txt");
}
});

// Print count array elements
    System.out.println("Length : " + matchingFiles.length + " ");

Here I never call the deleteOnExit() (but file delete automtically)OR JVM automatically delete the file? By the way its deleted automatically if is it possible to avoid deleting the file? or any other ways to do my requirement?

Upvotes: 0

Views: 687

Answers (1)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

File.createTempFile only creates files with unique names, other than that they are just regular files. They are not deleted automatically. It is explained in File.createTempFile API: This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit method

Upvotes: 1

Related Questions