001package edu.pdx.cs410J.java8;
002
003import java.io.IOException;
004import java.io.UncheckedIOException;
005import java.nio.file.Files;
006import java.nio.file.Path;
007import java.nio.file.Paths;
008import java.util.Comparator;
009import java.util.stream.Stream;
010
011public class PrintLargestFiles {
012
013  public static void main(String[] args) throws IOException {
014    Path path = Paths.get(args[0]);
015
016    printLargestFiles(path);
017  }
018
019  private static void printLargestFiles(Path root) throws IOException {
020    Stream<Path> stream = Files.walk(root);
021    stream
022      .sorted(new FileSizeComparator().reversed())
023      .limit(10)
024      .forEach(PrintLargestFiles::printFileAndSize);
025  }
026
027  private static void printFileAndSize(Path path) {
028    try {
029      System.out.println(Files.size(path) + " " + path);
030    } catch (IOException e) {
031      throw new UncheckedIOException(e);
032    }
033
034  }
035
036  private static class FileSizeComparator implements Comparator<Path> {
037    @Override
038    public int compare(Path o1, Path o2) {
039      try {
040        long size1 = Files.size(o1);
041        long size2 = Files.size(o2);
042        return size1 > size2 ? 1 : (size2 > size1 ? -1 : 0);
043      } catch (IOException ex) {
044        throw new UncheckedIOException(ex);
045      }
046    }
047  }
048}