This Java program is all contained in the main() method, but it uses classes from 3 different locations. We have 3 import statements at the top to make those classes easier to access.
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class Program {
public static void main(String[] args) {
// Step 1: create ArrayList of records to store file data.
record SizeData (Path name, long size) {}
var items = new ArrayList<SizeData>();
// Step 2: get path.
var path = FileSystems.getDefault().getPath(
"programs");
// Step 3: loop over files in a directory.
try (var stream = Files.newDirectoryStream(path)) {
// Step 4: store the file size of each path in a record, and add it to the ArrayList.
for (Path entry : stream) {
var size = Files.size(entry);
items.add(new SizeData(entry, size));
}
} catch (IOException exception) {
}
// Step 5: use lambda expression with Collections.sort.
Collections.sort(items, (a, b) -> Long.compare(b.size, a.size));
// Step 6: display files sorted by size.
for (var item : items) {
System.out.println(item);
}
}
}
SizeData[name=programs/words.txt, size=1743328]
SizeData[name=programs/Program.java, size=1114]
SizeData[name=programs/program.js, size=812]
SizeData[name=programs/program.go, size=723]
SizeData[name=programs/program.scala, size=676]
SizeData[name=programs/program.php, size=619]
SizeData[name=programs/program.py, size=515]
SizeData[name=programs/program.rb, size=247]
SizeData[name=programs/program.swift, size=79]
SizeData[name=programs/example.txt, size=18]