次のような単純な 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();
}
}
}
ファイナライズメソッドでクリーンアップを実装すると、GC がオブジェクトを破棄するときに一時ファイルが自動的に削除されると思いました。
これをデバッグしてみましたが、ファイナライズメソッドが呼び出されていないようです。
どういう理由ですか?これは、これを Tomcat サーバーにデプロイしているためでしょうか?
乾杯