我创建了一个简单的 Java 类,如下所示:
我将内容作为字节数组和文件名传递,该类在某处创建一个 TempFile。
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class TempFile {
private byte[] content;
private File file;
private String fileName;
public TempFile(byte[] content, String fileName)
throws IOException {
this.content = content;
this.fileName = fileName;
file = createTempFile();
}
private File createTempFile()
throws IOException {
String tmpDir = System.getProperty("java.io.tmpdir");
if(!tmpDir.endsWith("/") || !tmpDir.endsWith("\\"))
tmpDir += "/";
File tmpfile = new File(tmpDir + createUniqueName());
while(tmpfile.exists())
tmpfile = new File(tmpDir + createUniqueName());
tmpfile.createNewFile();
FileUtils.writeByteArrayToFile(tmpfile, content);
return tmpfile;
}
@Override
protected void finalize() throws Throwable {
try {
if(file.exists() && file.canRead() && file.canWrite())
file.delete();
} catch(Throwable t) {
t.printStackTrace();
} finally {
super.finalize();
}
}
}
我想如果我在 finalize 方法中实现清理,那么当 GC 处理对象时,临时文件将被自动删除。
我尝试对此进行调试,但似乎未调用 finalize 方法。
什么原因?这可能是因为我正在部署这个 Tomcat 服务器吗?
干杯