名称的最大长度是多少TempFile
在java中和MaximumFilesize
取决于
在我们提到要创建的临时目录或其他基于java的机器上?
何时致电deleteOnExit()
方法---但是这个方法有什么用,因为它会在 JVM 关闭时被调用。但是在生产中,基于服务器将 24*7 运行。因此文件将连续创建,这对于我们创建的服务器来说将是一个问题文件因为内存。
要自动清理早于(修改)X秒的临时文件...
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
public class FileAutoCleaner {
final static FileAutoCleaner singleton = new FileAutoCleaner();
final HashSet<File> bag = new HashSet<File>();
public static FileAutoCleaner getInstance() {
return singleton;
}
// This create the temp file and add to bag for checking
public synchronized File createTempFile(String prefix, String suffix) throws IOException {
File tmp = File.createTempFile(prefix, suffix);
tmp.deleteOnExit();
bag.add(tmp);
return tmp;
}
// Periodically call this function to clean old files
public synchronized void cleanOldFiles(final int secondsOld) {
long now = (System.currentTimeMillis() / 1000);
for (File f : bag) {
long expired = (f.lastModified() / 1000) + secondsOld;
if (now >= expired) {
System.out.println("Deleted file=" + f.getAbsolutePath());
f.delete();
bag.remove(f);
}
}
}
public static void main(String[] args) throws Exception {
FileAutoCleaner fac = FileAutoCleaner.getInstance();
System.out.println(System.currentTimeMillis() / 1000);
fac.createTempFile("deleteme", "tmp");
for (int i = 0; i < 5; i++) {
System.out.println(System.currentTimeMillis() / 1000);
// delete if older than 2 seconds
fac.cleanOldFiles(2);
Thread.sleep(1000);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)