简体   繁体   English

如何避免使用Java删除Temp文件?

[英]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. 当阅读此链接时,我会得到一些信息,通常当您显式调用deleteOnExit()时,临时文件不会被删除,但是当我的JVM完成后,临时文件会自动删除。

//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? 在这里,我从不调用deleteOnExit() (而是自动删除文件)还是JVM自动删除文件? By the way its deleted automatically if is it possible to avoid deleting the file? 顺便说一下,是否有可能避免删除文件而将其自动删除? or any other ways to do my requirement? 或任何其他方式来满足我的要求?

File.createTempFile only creates files with unique names, other than that they are just regular files. File.createTempFile仅创建具有唯一名称的文件,而不仅仅是常规文件。 They are not deleted automatically. 它们不会自动删除。 It is explained in File.createTempFile API: This method provides only part of a temporary-file facility. File.createTempFile API中对此进行了说明: 此方法仅提供临时文件工具的一部分。 To arrange for a file created by this method to be deleted automatically, use the deleteOnExit method 若要安排自动删除通过此方法创建的文件,请使用deleteOnExit方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM