파일 삭제 코드를 간단하게 짜면 아래와 같다
String location = "경로";
String fileName = "파일이름";
// C:\\fileRepository\ + test.png 이런 식
File file = new File(location + fileName);
file.delete();
삭제하려는 파일이나 디렉토리가 다른 파일에 의해서 사용중이면
파일은 삭제되지 않고 false.
해결법 1 강제 삭제
String location = "경로";
String fileName = "파일이름";
File file = new File(location + fileName);
// 추가
System.gc();
System.runFinalization();
file.delete();
강제로 GC 를 실행시키는 방법이다.
GC = Garbage Collection
하지만 원인을 파악하기 쉽지 않다.
해결법2 원인 찾기
String location = "경로";
String fileName = "파일이름";
Path filePath = paths.get(location + fileName);
// delete
// 삭제 대상이 없으면 NoSuchFileException
// 디렉토리가 안 비어있으면 DirectoryNotEmptyException
// 파일을 다른 곳에서 잡고 있으면 Exception
try{
Files.delete(filePath);
}catch(NoSuchFileException e){
//directory or file 없을 때
}catch(DirectoryNotEmptyException e){
// directory 비어있지 않을 때
}catch(IOException e){
e.printStackTrace();
}
// deleteIfExists
// 파일 존재 유무에 따라 삭제 or false
try{
Files.deleteIfExists(filePath);
}catch(DirectoryNotEmptyException e){
// directory 비어있지 않을 때
}catch(IOException e){
e.printStackTrace();
}
Files 를 사용하면 파일을 삭제할 수 없는 경우에 Exception을 발생시켜 주기 때문에
원인을 파악가능