Ela*_*da2 2 java lambda file filter
我想用获取 afile path和 a的方法编写代码file name prefix
并删除dir path其中file name prefix除 10 个最新文件外的所有文件。
我想使用 lambda (java 8)
但我不确定如何过滤 10 个最近的文件:
public Optional<File> getLatestFileFromDir(String baseLineFileName) {
File baseLineFile = new File(baseLineFileName);
File dir = baseLineFile.getParentFile();
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
return null;
}
return Arrays.asList(dir.listFiles()).stream()
.filter(file -> isNameLikeBaseLine(file, baseLineFile.getName()))
.max(new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
int answer;
if (o1.lastModified() == o2.lastModified()) {
answer = 0;
} else if (o1.lastModified() > o2.lastModified()) {
answer = 1;
} else {
answer = -1;
}
return answer;
}
});
}
Run Code Online (Sandbox Code Playgroud)
请找到一个完整的工作示例
.
public class KeepTopTenFiles {
public static void main(String[] args) throws IOException {
ArrayList<File> files = new ArrayList<>();
createDummyFiles(files);
Collections.shuffle(files);
files.stream()
.filter((File p) -> p.getName().matches("foobar_.*"))
.sorted(getReverseLastModifiedComparator())
.skip(10)
// to delete the file but keep the most recent ten
// .forEach(x -> ((File) x).delete());
// or display the filenames which would be deleted
.forEach((x) -> System.out.printf("would be deleted: %s%n", x));
}
private static Comparator<File> getReverseLastModifiedComparator() {
return (File o1, File o2) -> {
if (o1.lastModified() < o2.lastModified()) {
return 1;
}
if (o1.lastModified() > o2.lastModified()) {
return -1;
}
return 0;
};
}
private static void createDummyFiles(ArrayList<File> files) throws IOException {
long timestamp = System.currentTimeMillis();
int filesToCreate = 30;
for (int i = 0; i < filesToCreate; i++) {
long lastModified = timestamp + 5 * i;
String fileName = String.format("foobar_%02d", i);
File file = new File(fileName);
file.createNewFile();
file.setLastModified(lastModified);
files.add(file);
}
}
}
Run Code Online (Sandbox Code Playgroud)