code

Java 임시 파일은 언제 삭제됩니까?

codestyles 2020. 10. 14. 07:50
반응형

Java 임시 파일은 언제 삭제됩니까?


메소드를 사용하여 Java에서 임시 파일을 작성한다고 가정하십시오.

File tmp = File.createTempFile(prefix, suffix);

delete()메서드를 명시 적으로 호출하지 않으면 언제 파일이 삭제됩니까?

직관적으로 JVM이 종료되거나 이전에 (가비지 수집기에 의해) 또는 나중에 (일부 운영 체제 스위핑 프로세스에 의해 ) 종료 될 수 있습니다 .


파일은 JavaDoc 에서 자동으로 삭제되지 않습니다 .

이 방법은 임시 파일 기능의 일부만 제공합니다. 이 메서드로 만든 파일을 자동으로 삭제하려면 deleteOnExit () 메서드를 사용합니다.

따라서 명시 적으로 deleteOnExit ()를 호출해야합니다 .

가상 머신이 종료 될 때이 추상 경로 이름으로 표시된 파일 또는 디렉토리를 삭제하도록 요청합니다.


다른 답변에서 알 수 있듯이로 만든 임시 파일 File.createTempFile()명시 적으로 요청하지 않는 한 자동으로 삭제 되지 않습니다 .

이 작업을 수행 할 수있는 일반적인 휴대용 방법은 호출하는 것입니다 .deleteOnExit()FileJVM이 종료 될 때 삭제 파일을 예약 할 객체. 그러나이 방법의 약간의 단점은 VM이 정상적으로 종료되는 경우에만 작동한다는 것입니다. 비정상 종료 (예 : VM 충돌 또는 VM 프로세스 강제 종료)시 파일은 삭제되지 않은 상태로 남아있을 수 있습니다.

Unixish 시스템 (예 : Linux)에서는 임시 파일 을 연 후 즉시 삭제하여 다소 안정적인 솔루션을 얻을 수 있습니다 . 이것은 Unix 파일 시스템이 파일이 하나 이상의 프로세스에 의해 열려있는 동안 삭제 ( 정확하게는 unlinked )를 허용하기 때문에 작동 합니다. 이러한 파일은 열린 파일 핸들을 통해 정상적으로 액세스 할 수 있으며 디스크에서 차지하는 공간은 파일에 대한 열린 핸들을 보유한 마지막 프로세스가 종료 된 후에 만 ​​OS에 의해 회수됩니다.

프로그램이 종료 된 후 임시 파일이 제대로 삭제되도록하는 가장 안정적이고 이식 가능한 방법은 다음과 같습니다.

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

public class TempFileTest
{
    public static void main(String[] args)
    {
        try {
            // create a temp file
            File temp = File.createTempFile("tempfiletest", ".tmp"); 
            String path = temp.getAbsolutePath();
            System.err.println("Temp file created: " + path);

            // open a handle to it
            RandomAccessFile fh = new RandomAccessFile (temp, "rw");
            System.err.println("Temp file opened for random access.");

            // try to delete the file immediately
            boolean deleted = false;
            try {
                deleted = temp.delete();
            } catch (SecurityException e) {
                // ignore
            }

            // else delete the file when the program ends
            if (deleted) {
                System.err.println("Temp file deleted.");
            } else {
                temp.deleteOnExit();
                System.err.println("Temp file scheduled for deletion.");
            }

            try {
                // test writing data to the file
                String str = "A quick brown fox jumps over the lazy dog.";
                fh.writeUTF(str);
                System.err.println("Wrote: " + str);

                // test reading the data back from the file
                fh.seek(0);
                String out = fh.readUTF();
                System.err.println("Read: " + out);

            } finally {
                // close the file
                fh.close();
                System.err.println("Temp file closed.");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Unixish 시스템에서이를 실행하면 다음과 같은 출력이 생성됩니다.

Temp file created: /tmp/tempfiletest587200103465311579.tmp
Temp file opened for random access.
Temp file deleted.
Wrote: A quick brown fox jumps over the lazy dog.
Read: A quick brown fox jumps over the lazy dog.
Temp file closed.

반면 Windows에서는 출력이 약간 다르게 보입니다.

Temp file created: C:\DOCUME~1\User\LOCALS~1\Temp\tempfiletest5547070005699628548.tmp
Temp file opened for random access.
Temp file scheduled for deletion.
Wrote: A quick brown fox jumps over the lazy dog.
Read: A quick brown fox jumps over the lazy dog.
Temp file closed.

In either case, however, the temp file should not remain on the disk after the program has ended.


Ps. While testing this code on Windows, I observed a rather surprising fact: apparently, merely leaving the temp file unclosed is enough to keep it from being deleted. Of course, this also means that any crash that happens while the temp file is in use will cause it to be left undeleted, which is exactly what we're trying to avoid here.

AFAIK, the only way to avoid this is to ensure that the temp file always gets closed using a finally block. Of course, then you could just as well delete the file in the same finally block too. I'm not sure what, if anything, using .deleteOnExit() would actually gain you over that.


If I do not explicity call the delete() method, when will the file be deleted?

It won't, at least not by Java. If you want the file to be deleted when the JVM terminates then you need to call tmp.deleteOnExit().


from: How to delete temporary file in Java

Temporary file is used to store the less important and temporary data, which should always be deleted when your system is terminated. The best practice is use the File.deleteOnExit() to do it.

For example,

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

The above example will create a temporary file named “abc.tmp” and delete it when the program is terminated or exited.

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


Temporary file is used to store the less important and temporary data, which should always be deleted when your system is terminated. The best practice is use the File.deleteOnExit() to do it.

For example,

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

The above example will create a temporary file named “abc.tmp” and delete it when the program is terminated or exited.


You can manually delete the file before terminating the process if you want to, however when the process is terminated the file will be deleted as well.

참고URL : https://stackoverflow.com/questions/16691437/when-are-java-temporary-files-deleted

반응형