본문 바로가기
Program/JAVA

폴더 삭제 : 삭제.(FileUtils.cleanDirectory()와 File.delete())

by Woodland 2019. 12. 23.

 

JAVA 에서 File처리를 할때, 특정 폴더에 있는 파일을들 모두 지워야 하는 순간이 있다.
기존의 JAVA UTIL에서 지원하는 FILE객체에 포함되어있는 delete() 메서드를 이용하면 특정 파일을 지울 수 있다.
이는 비단 파일 뿐만 아니라 폴더에도 해당되는데, 폴더를 지우기 위해서는 해당 폴더 하위에 아무런 파일이 없어야 한다.

 

다음은 JAVA.UTIL API 도큐먼트의 설명이다.

 

 

Files.delete(path)관련 도큐멘드

Deleting a File or Directory

You can delete files, directories or links. With symbolic links, the link is deleted and not the target of the link. With directories, the directory must be empty, or the deletion fails.

=> 일이나 디렉토리, 링크를 지울수 있다. 타겟의 링크가 아니라, 경로를 넣으면 경로 자체를 지울 수 있지만, 해당 폴더가 비어있어야 한다. 그렇지 않으면 삭제 실패가 뜬다.



The Files class provides two deletion methods.
The delete(Path) method deletes the file or throws an exception if the deletion fails. For example, if the file does not exist a NoSuchFileException is thrown. You can catch the exception to determine why the delete failed as follows:

 

 

try { Files.delete(path); } catch (NoSuchFileException x) { System.err.format("%s: no such" + " file or directory%n", path); } catch (DirectoryNotEmptyException x) { System.err.format("%s not empty%n", path); } catch (IOException x) { // File permission problems are caught here. System.err.println(x); }

 

=> 해당 메서드의 경우 대게 3가지의 Exception을 뱉어내는데,
1. NoSuchFileException : 그런 파일 없음
2. DirectoryNotEmptyException : 경로가 비어있지 않음.
3. IOException : 입출력 오류

이다. 따라서 특정 파일의 상위 폴더를 삭제하고자 할 때에는 해당 메서드를 사용할 수 없다.
FileUtils.cleanDirectory()

위와같은 상황에서 쓸 수 있는 도구가 바로 FileUtils.cleanDirectory()이다.


 

FileUtils는 아파치에서 지원하는 FIle을 다루는 툴로서, 유용한 기능이 많이 있다.

사용법은 다음과 같다.

우선 자바 파일 맨 상단에
org.apache.commons.io.FileUtils
import 후에

FileUtils.cleanDirectory(new File("다운로드 경로"));
와 같은 표현으로 사용이 가능하다.

해당 코드를 이용하면 지정한 경로 뿐만 아니라 하위 경로까지 모두 삭제해준다.

해당 메서는 아래와 같이 2개의 Exception을 뱉어낸다.
IOException - in case cleaning is unsuccessful (입출력 예외 : 삭제가 모종의 이유로 실패하였을때)
IllegalArgumentException - if directory does not exist or is not a directory (잘못된 인자 예외 : 인자로 받은 경로가 존재하지 않거나, 양식이 경로가 아닐때)

특정 파일을 확실하게 삭제하고 싶다면 앞으로는 위와같은 방법을 쓰는것도 좋을것 같다.

'Program > JAVA' 카테고리의 다른 글

2중배열 정렬  (0) 2018.12.09
split()에 관하여  (0) 2018.11.12
배열 복사 : clone()과 arraycopy()의 차이  (0) 2018.09.03
키벨류값을 정렬해주는 메서드.  (0) 2018.08.21
hasNextLine()에 관하여  (0) 2017.07.07