user11652798
user11652798

Reputation:

Not deleting the files

I have this method here. I want to list all the files in a specific folder. I want to read them all and if a file has a line with more than 5 characters I want to delete it. What am I doing wrong?

public void read() throws IOException {
    File[] fajllat = folder.listFiles((File f) -> f.isFile());
    int count = 0;
    String line = null;
    for (File file : fajllat) {
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        while ((line = br.readLine()) != null) {
            if (line.length() > 5) {
              count++;
              file.delete();
            }
        }
    }

    FileWriter fw = new FileWriter("C://Users//Admin//Desktop//foldtest123");
    BufferedWriter bw = new BufferedWriter(fw);
    try (PrintWriter pw = new PrintWriter(bw)) {
        pw.println(count);
        pw.close();
    }
}

Upvotes: 2

Views: 65

Answers (2)

Ashish
Ashish

Reputation: 209

Are you checking using the boolean result of file.delete() if the file is being deleted or not? I think you should do that. Also, once a file is deleted, break the while loop and go on to the next file. I have modified the code including the above two findings.

File directory = new File("XXXX/XXXX/XXXX/XXXX/");
    if(!directory.isDirectory()) {
        System.out.println("Given file is not a directory");
        return;
    }
    String line;
    int count = 0;
    File[] fileList = directory.listFiles(File::isFile);
    if(fileList != null && fileList.length > 0) {
        for (File file : fileList) {
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            while ((line = br.readLine()) != null) {
                if (line.length() > 5) {
                    count++;
                    boolean wasFileDeleted = file.delete();
                    if(wasFileDeleted) {
                        System.out.println("The file "+file.getName()+" was deleted");
                    } else {
                        System.out.println("The file "+file.getName()+" deletion did not succeed");
                    }
                    break;
                }
            }
        }
    }
    System.out.println("A total of "+count+" files were deleted");

I was able to delete all files within a directory using the same code you are using. This was in a mac. Please post if you are getting any errors while deleting.

Upvotes: 0

George Z.
George Z.

Reputation: 6808

In order to see what is going wrong and the file does not being deleted, use Files.delete(file.toPath()); instead of File#delete method. java.nio.Files#delete method will throw an exception, and then you will be able to know...

Also, worth to read: this question.

Upvotes: 1

Related Questions