文件未删除

时间:2014-01-28 07:03:58

标签: java

尝试删除以名称TRTHIndicative _。

开头的文件夹中的特定文件

但文件没有删除,我使用下面的代码

testMethod(inputDir);
testMethod(outputFile);


private static void testMethod(String dirName){
    File directory = new File(dirName);

    // Get all files in directory
    File[] files = directory.listFiles();
    for (File file : files) {

        if (file.getName().startsWith("Indicative_")) {
            // Delete each file
            if(file.exists()){
                System.out.println("File is there!");
            }
            if (file.delete()) {
                // Failed to delete file
                System.out.println("Failed to delete " + file);
            } else {
                System.out.println("Deleted file succsfully");
            }
        }

    }

如果有任何问题,请检查并告诉我。

3 个答案:

答案 0 :(得分:1)

如果文件成功已删除,则您ifelse混淆 - File#delete()返回true。因此,条件应该颠倒过来:

if (file.delete()) {
    System.out.println("Deleted file succesfully");
} else {
    // Failed to delete file
    System.out.println("Failed to delete " + file);
}

答案 1 :(得分:1)

Mureinik是对的。 我只是尝试了你的代码和平。它工作正常。只需进行如下更改:

public class Main {

public static void main(String[] args) {
    File directory = new File("C:/temp");
    File[] files = directory.listFiles();
    for (File file : files) {

        if (file.getName().toLowerCase().startsWith("blub")) {
            // Delete each file
            if (file.exists()) {
                System.out.println("File is there!");
            }
            if (file.delete()) {
                System.out.println("Deleted file succsfully");
            } else {
                // Failed to delete file
                System.out.println("Failed to delete " + file);
            }
        }
    }
}

}

请注意我添加的 toLowerCase()。这将使您的代码段更易于使用。

答案 2 :(得分:0)

我认为您尝试删除的文件中存在权限错误。 elToro的回答也适合我。 尝试为每个用户提供读/写权限 how to change file permissions in windows