[英]I don´t know how to change my program so that i can see the ten largest files
I need to program some statistics, like Count files etc. But I have a problem with one of the tasks: Write code to identify the 10 largest Files.我需要编写一些统计数据,例如对文件进行计数等。但我在其中一项任务中遇到了问题:编写代码以识别 10 个最大的文件。
My Problem is that I don´t know how to get started.我的问题是我不知道如何开始。 I have code to get the largest file.
我有代码来获取最大的文件。 But how i can get the ten largest files ?
但是我怎样才能得到十个最大的文件呢? Here is one class that shows the largest file.
这是一个显示最大文件的类。
@Override
public String getDescription() {
return "find largest file";
}
@Override
public void printResults(List<File> files) {
File largest = files.get(0);
for (File f : files)
if (f.length() > largest.length())
largest = f;
System.out.println("Largest file: " + largest.getName() + " (" + largest.length() + " bytes)");
}
You can sort the files by file size and get the first 10 elements.您可以按文件大小对文件进行排序并获取前 10 个元素。 Note that you will get strange results with this code if any of your files are really big:
请注意,如果您的任何文件非常大,您将使用此代码得到奇怪的结果:
@Override
public void printResults(List<File> files) {
files.sort((file1,file2) -> (int)(file1.length()-file2.length())); // This will NOT work correctly if any of the files are over 2.7 GB in size.
List<File> largest = files.subList(0, files.size() > 10 ? 10 : files.size());
System.out.println("Largest files:");
for(File file : largest) {
System.out.println(file.getName() + " (" + file.length() + " bytes)");
}
}
You can use the Java Stream API to sort and limit the file list:您可以使用 Java Stream API 对文件列表进行排序和限制:
files.stream()
.sorted(Comparator.comparingLong(File::length).reversed())
.limit(10)
.forEach(f -> System.out.println(f.getName() + " (" + f.length() + " bytes)"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.