I need to filter out the files in a directory that end with "_done".
The directory contains three .txt files, namely format1.txt , format2.txt and format2_done.txt that needs to be filtered out.
The following sample correctly lists all the files:
System.out.println("all files: ");
String[] files = folder.list();
for (String item : files) {
System.out.println(item);
}
Output:
all files:
format1.txt
format2.txt
format2_done.txt
But the following sample:
System.out.println("filtered: ");
String[] filteredFiles = folder.list((File folder, String name)
-> {return !(name.matches("_done.txt>"));});
for (String item : filteredFiles) {
System.out.println(item);
}
produces the same output and doesn't filter anything:
filtered:
format1.txt
format2.txt
format2_done.txt
What am I doing wrong?
Try to use this regex instead .*_done\\\\.txt$
like this :
String[] filteredFiles = folder.list((File folder, String name)
-> !name.matches(".*_done\\.txt$")
);
details :
.*
zero or more character _done\\\\.txt
, note that you should to escape the dot with \\\\
$
end anchor Or you can just use String::endsWith :
String[] filteredFiles = folder.list((File folder, String name)
-> !name.endsWith("_done.txt")
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.