programming

[파일 시스템] 파일 삭제 코드

롯대쌍쌍바 2023. 2. 8. 10:06

디렉터리에 저장된 파일을 모두 삭제하고 싶을 때 사용할 수 있는 코드다.

    public static void deleteDirectory(File directory) {
        // Get a list of all the files in the directory
        File[] files = directory.listFiles();

        // If the directory is not empty, delete its contents
        if (files != null) {
            for (File file : files) {
                // If the file is a directory, recursively delete its contents
                if (file.isDirectory()) {
                    deleteDirectory(file);
                }
                // Otherwise, delete the file
                else {
                    file.delete();
                }
            }
        }

        // Delete the empty directory
        directory.delete();
    }