Delete Files with same Prefix String using Java

前端 未结 11 1719
梦谈多话
梦谈多话 2020-12-16 09:11

I have around 500 text files inside a directory with a same prefix in their filename say dailyReport_.

The latter part of the file is the date of the fi

相关标签:
11条回答
  • 2020-12-16 09:51

    Use FileFilter like so:

    File dir = new File(<path to dir>);
    File[] toBeDeleted = dir.listFiles(new FileFilter() {
      boolean accept(File pathname) {
         return (pathname.getName().startsWith("dailyReport_08") && pathname.getName().endsWith(".txt"));
      } 
    
    for (File f : toBeDeleted) {
       f.delete();
    }
    
    0 讨论(0)
  • 2020-12-16 09:55

    or in scala

    new java.io.File(<<pathStr>>).listFiles.filter(_.getName.endsWith(".txt")).foreach(_.delete())
    
    0 讨论(0)
  • 2020-12-16 09:58

    You can't do it without a loop. But you can enhance this loop. First of all, ask you a question: "what's the problem with searching and removing in the loop?" If it's too slow for some reason, you can just run your loop in a separate thread, so that it will not affect your user interface.

    Other advice - put your daily reports in a separate folder and then you will be able to remove this folder with all content.

    0 讨论(0)
  • 2020-12-16 10:00

    You can use a loop

    for (File f : directory.listFiles()) {
        if (f.getName().startsWith("dailyReport_")) {
            f.delete();
        }
    }
    
    0 讨论(0)
  • 2020-12-16 10:01

    There isn't a wildcard but you can implement a FilenameFilter and check the path with a startsWith("dailyReport_"). Then calling File.listFiles(filter) gives you an array of Files that you can loop through and call delete() on.

    0 讨论(0)
  • 2020-12-16 10:01

    I know I'm late to the party. However, for future reference, I wanted to contribute a java 8 stream solution that doesn't involve a loop.

    It may not be pretty. I welcome suggestions to make it look better. However, it does the job:

    Files.list(deleteDirectory).filter(p -> p.toString().contains("dailyReport_08")).forEach((p) -> {
        try {
            Files.deleteIfExists(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    

    Alternatively, you can use Files.walk which will traverse the directory depth-first. That is, if the files are buried in different directories.

    0 讨论(0)
提交回复
热议问题