Javaで一時ファイルを削除する方法

Javaで一時ファイルを削除する方法

一時ファイルは、重要度の低い一時データを保存するために使用されます。これらのデータは、システムの終了時に常に削除する必要があります。 ベストプラクティスは、File.deleteOnExit()を使用して実行することです。

例えば、

File temp = File.createTempFile("abc", ".tmp");
temp.deleteOnExit();

上記の例では、「abc.tmp」という名前の一時ファイルを作成し、プログラムが終了または終了したときにそれを削除します。

P.S If you want to delete the temporary file manually, you can still use the File.delete().

package com.example.file;

import java.io.File;
import java.io.IOException;

public class DeleteTempFileExample
{
    public static void main(String[] args)
    {

        try{

           //create a temp file
           File temp = File.createTempFile("temptempfilefile", ".tmp");

           //delete temporary file when the program is exited
           temp.deleteOnExit();

           //delete immediate
           //temp.delete();

        }catch(IOException e){

           e.printStackTrace();

        }

    }
}