Delete all files with an extension using Java

后端 未结 5 1373
自闭症患者
自闭症患者 2021-02-15 11:52

I\'m (relatively) new to Java and I\'m trying to implement a .jar that runs a list of commands that in Windows XP\'s command prompt it would be:

cd\\
cd myfolder         


        
相关标签:
5条回答
  • 2021-02-15 12:37
    for (File f : folder.listFiles()) {
        if (f.getName().endsWith(".lck")) {
            f.delete(); // may fail mysteriously - returns boolean you may want to check
        }
    }
    
    0 讨论(0)
  • 2021-02-15 12:38

    Java 8 approach

    Arrays.stream(yourDir.listFiles((f, p) -> p.endsWith("YOUR_FILE_EXTENSION"))).forEach(File::delete);    
    
    0 讨论(0)
  • 2021-02-15 12:45

    fList.get(i) should be fList[i] as fList is an array, and it returns a File reference not a String.

    Change: -

    String pes = fList.get(i);
    

    to: -

    File pes = fList[i];
    

    And then change if (pes.contains(".lck") == true) to
    if (pes.getName().contains(".lck"))

    In fact, since you are checking for the extension, you should use endsWith method rather than contains method. And yes, you don't need to compare your boolean value with ==. So just use this condition: -

    if (pes.getName().endsWith(".lck")) {
        boolean success = (new File(fList.get(i)).delete());
    }
    
    0 讨论(0)
  • 2021-02-15 12:45

    You are using Collection method get on an Array. Use Array Index notation as below:

            File pes = fList[i];
    

    Also better to use endsWith() String method over the file name as:

       if (pes.getName().endsWith(".lck")){
          ...
       }
    
    0 讨论(0)
  • 2021-02-15 12:48

    Final Code which works :)

    File folder = new File(dir);
                    File fList[] = folder.listFiles();
    
                    for (File f : fList) {
                        if (f.getName().endsWith(".png")) {
                            f.delete(); 
                        }}
    
    0 讨论(0)
提交回复
热议问题