Sort
files, sizeWhat are the largest files in a folder? In Java we can list the files in a directory with Files.newDirectoryStream
, and then with records, we can sort the data.
With a lambda expression, we can use Collections.sort
to order an ArrayList
's contents. This allows us to sort by file size in ascending, and descending, order.
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.
SizeData
. We place the files in an ArrayList
.Path
class
instance for a directory on the disk. When running this program, change the path to one that exists.Files.newDirectoryStream
to loop over the files in the directory. We use a try-catch
block as this may throw an exception.Path
, and then store that data along with the Path
in a record. We add the record to the ArrayList
.Collections.sort
, passing a lambda expression with Long.compare
to order the records in the ArrayList
by the size field.ArrayList
. Files are ordered from largest to smallest.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]
To change the sort order to ascending (low to high), we can swap the arguments to Long.compare
. We then have a ascending sort.
Sometimes the most important files are also the largest ones. By sorting files by their sizes, we can gain insight into which files may be the most important ones.