[java] 파일 삭제 및 디렉토리 삭제 예외 처리하기

파일 및 디렉토리를 삭제하는 작업은 자주 발생하는 작업 중 하나입니다. 하지만 삭제 작업은 예외가 발생할 수 있는 작업이기도 합니다. 따라서 파일 삭제 및 디렉토리 삭제 작업을 수행할 때에는 예외 처리를 확실하게 해주어야 합니다.

파일 삭제 예외 처리하기

Java에서 파일을 삭제하는 작업은 java.io.File 클래스를 사용합니다. 파일을 삭제할 때에는 delete() 메서드를 호출하면 됩니다. 하지만 파일이 존재하지 않을 경우, 삭제 작업이 실패할 수 있습니다.

아래는 파일 삭제 작업을 수행할 때 예외 처리를 하는 예제 코드입니다.

import java.io.File;

public class FileDeletionExample {

    public static void deleteFile(String filePath) {
        File file = new File(filePath);
        try {
            if (file.delete()) {
                System.out.println(filePath + " 파일이 삭제되었습니다.");
            } else {
                System.out.println(filePath + " 파일이 존재하지 않습니다.");
            }
        } catch (Exception e) {
            System.out.println(filePath + " 파일 삭제 중 오류가 발생했습니다: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        String filePath = "C:/Path/To/File.txt";
        deleteFile(filePath);
    }
}

위의 예제 코드에서는 파일 삭제 작업 중에 발생하는 예외를 catch 블록에서 처리하고 있습니다. 만약 파일 삭제 작업 중 예외가 발생하면 해당 예외 객체를 사용하여 에러 메시지를 출력하고, 작업이 실패했음을 알려줍니다.

디렉토리 삭제 예외 처리하기

디렉토리를 삭제하는 작업도 마찬가지로 예외가 발생할 수 있는 작업입니다. Java에서 디렉토리를 삭제하는 작업은 java.io.File 클래스의 delete() 메서드를 이용하면 됩니다.

아래는 디렉토리 삭제 작업을 수행할 때 예외 처리를 하는 예제 코드입니다.

import java.io.File;

public class DirectoryDeletionExample {

    public static void deleteDirectory(String directoryPath) {
        File directory = new File(directoryPath);
        try {
            if (directory.isDirectory()) {
                if (directory.list().length == 0) {
                    directory.delete();
                    System.out.println(directoryPath + " 디렉토리가 삭제되었습니다.");
                } else {
                    String[] files = directory.list();
                    for (String fileName : files) {
                        File file = new File(directoryPath + File.separator + fileName);
                        file.delete();
                    }
                    directory.delete();
                    System.out.println(directoryPath + " 디렉토리와 그 안의 파일들이 모두 삭제되었습니다.");
                }
            } else {
                System.out.println(directoryPath + " 경로는 디렉토리가 아닙니다.");
            }
        } catch (Exception e) {
            System.out.println(directoryPath + " 디렉토리 삭제 중 오류가 발생했습니다: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        String directoryPath = "C:/Path/To/Directory";
        deleteDirectory(directoryPath);
    }
}

위의 예제 코드에서는 디렉토리 삭제 작업 중에 발생하는 예외를 catch 블록에서 처리하고 있습니다. 예외가 발생할 경우 해당 예외 객체를 사용하여 에러 메시지를 출력하고, 작업이 실패했음을 알려줍니다.

결론

파일 및 디렉토리 삭제 작업은 예외가 발생할 수 있는 작업이므로 예외 처리를 확실하게 해주어야 합니다. 예제 코드를 참고하여 파일 및 디렉토리 삭제 작업을 수행할 때 예외 처리를 포함시켜 안전하게 작업할 수 있도록 하세요.