on
【Java-파일】파일과 디렉토리 삭제
【Java-파일】파일과 디렉토리 삭제
1. 설명
이 포스트의 예제는 파일이나 디렉토리의 정보를 삭제하는 코드입니다.
File클래스에서 제공하는 삭제기능을 사용할 때 디렉토리의 삭제의 경우 디렉토리 안에 파일이나 디렉토리가 존재한다면,
디렉토리가 삭제되지 않는 문제가 있습니다.
이를 해결하기 위해 재귀적으로 파일과 디렉터리를 삭제하는 기능을 구현했습니다.
2. 소스코드
- 메서드
public boolean delete(File target) throws Exception { // 파일또는 디렉토리가 있는지 확인 if ( target.isFile() || target.isDirectory() ) { // 디렉토리 인지 확인 if (target.isDirectory()) { // 디렉토리안에 파일이 존재하면 디렉토리안의 파일을 먼저 삭제해야함 for (File f : target.listFiles()) { // 재귀적으로 파일 삭제 if ( !delete(f)) { throw new Exception("Caused by delete="+f.getAbsolutePath()); } } } if (target.delete()) { return true; } else { return false; } } else { return true; } } public boolean delete(String path) throws Exception { return delete(new File(path)); }
- 메인
public class File_10_Delete { public static void main(String[] args) { try { for (String str : args ) { System.out.println("Param : "+str); } String target = args[0]; FileUtil fu = new FileUtil(); System.out.println("Result " +fu.delete(target)); System.exit(0); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
3. 실행결과【Windows(이클립스) / Linux】
4. 전체코드
https://github.com/leeyoungseung/template-java
from http://koiking.tistory.com/35 by ccl(A) rewrite - 2021-09-13 02:27:36