如何只保存zip文件并使用java删除其他文件夹?

时间:2014-06-03 11:17:57

标签: java file directory delete-file

这里我有文件夹(书籍),我有3个子文件夹名为: sub1,sub2,sub3 sub1有2个文件 sub2有3个文件 sub3有4个文件 sub1.zip sub2.zip sub3.zip 。我想仅保留zip文件删除图书的sub1,sub2,sub3文件夹。使用我的代码,我能够删除sub1文件夹,sub2,sub3的所有内部文件,最后所有文件夹都变为空,然后如何删除sub1,sub2和sub3文件夹

public void SaveZipFiles(File destwithouAudio) throws IOException {
    File[] listOfFiles = destwithouAudio.listFiles();
    for (File listOfFile : listOfFiles) {
        if (listOfFile.getName().endsWith(".zip")) {
        } else {
            File FolderInside = new File(listOfFile.getAbsolutePath());
            File[] listOfFilesInside = FolderInside.listFiles();
            for (File listOfFilesInside1 : listOfFilesInside) {
                File deleteFolder = new File(listOfFilesInside1.getAbsolutePath());
                //System.out.println(""+listOfFilesInside[j]);
                RecursiveDelete(deleteFolder);
            }
        }
    }
}

RecursiveDelete方法代码是:

public static void RecursiveDelete(File file) throws IOException {
    if (file.isDirectory()) {
        if (file.list().length == 0) {
            file.delete();
            System.out.println("Directory is deleted : " + file.getAbsolutePath());
        } else {
            String files[] = file.list();
            for (String temp : files) {
                File fileDelete = new File(file, temp);
                RecursiveDelete(fileDelete);
            }
            if (file.list().length == 0) {
                file.delete();
                System.out.println("Directory is deleted : " + file.getAbsolutePath());
            }
        }
    } else {
        file.delete();
        System.out.println("File is deleted : " + file.getAbsolutePath());
    }
}

sub1,sub2,sub3 文件夹中删除所有文件后,我需要删除所有 sub1,sub2,sub3 文件夹。

在哪里更改代码?

1 个答案:

答案 0 :(得分:1)

public void deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete(); // The directory is empty now and can be deleted.
}

然后,您可以使用

public void SaveZipFiles(File destwithouAudio) { 
    File[] deletion = destwithouAudio.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            return !name.endsWith(".zip");
        }

    });
    for (File toDelete : deletion) {
        deleteDir(toDelete);
    }
}

(使用deleting folder from java文件夹删除)