Delete Files with same Prefix String using Java

前端 未结 11 1737
梦谈多话
梦谈多话 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 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.

提交回复
热议问题