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
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();
}
or in scala
new java.io.File(<<pathStr>>).listFiles.filter(_.getName.endsWith(".txt")).foreach(_.delete())
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.
You can use a loop
for (File f : directory.listFiles()) {
if (f.getName().startsWith("dailyReport_")) {
f.delete();
}
}
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.
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.