프로그래밍/JAVA

시스템 종료 후 File 삭제

AkaGeun 2018. 4. 12. 10:30

1. 파일 삭제

 - 시스템이 종료될 때 파일 삭제하고 싶음


2. Thread를 생성해서 처리함.

 - jdk1.8 미만

Runtime.getRuntime().addShutdownHook(new Thread() {

@Override
public void run() {
new File("").delete(); //File Delete Code

}
});


 - jdk 1.8 이상

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
new File("").delete(); //File Delete Code
}));

3. Apache Commons-io를 사용

 - 코드 샘플

try {
FileUtils.forceDeleteOnExit(new File("fileName"));
} catch (IOException e) {
e.printStackTrace();
}

 - 메소드

/**
* Schedules a file to be deleted when JVM exits.
* If file is directory delete it and all sub-directories.
*
* @param file file or directory to delete, must not be {@code null}
* @throws NullPointerException if the file is {@code null}
* @throws IOException in case deletion is unsuccessful
*/
public static void forceDeleteOnExit(final File file) throws IOException {
if (file.isDirectory()) {
deleteDirectoryOnExit(file);
} else {
file.deleteOnExit();
}
}