LearnFrenzy
Sign in Take a free test

File Handling, IO and NIO · File Handling Programs · Question 6

Summarise a folder by file extension in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Create a small project tree, then use Files.walk to count files and total bytes per extension (sorted), and find the largest file.

Solution
Main.java
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    static long size(Path p) {
        try { return Files.size(p); } catch (IOException e) { throw new UncheckedIOException(e); }
    }

    static String ext(Path p) {
        String n = p.getFileName().toString();
        int dot = n.lastIndexOf('.');
        return dot < 0 ? "(none)" : n.substring(dot + 1);
    }

    public static void main(String[] args) throws IOException {
        Path root = Files.createTempDirectory("proj");
        Files.createDirectories(root.resolve("src"));
        Files.createDirectories(root.resolve("docs"));
        Files.writeString(root.resolve("src/App.java"), "class App { }");
        Files.writeString(root.resolve("src/Util.java"), "class Util { static int x; }");
        Files.writeString(root.resolve("docs/guide.md"), "# Guide\nRead me first.");
        Files.writeString(root.resolve("README.md"), "# Project");
        Files.writeString(root.resolve("LICENSE"), "MIT");

        List<Path> files;
        try (Stream<Path> s = Files.walk(root)) { files = s.filter(Files::isRegularFile).toList(); }

        Map<String, long[]> byExt = files.stream().collect(Collectors.groupingBy(Main::ext, TreeMap::new,
            Collectors.reducing(new long[2], p -> new long[]{1, size(p)}, (a, b) -> new long[]{a[0] + b[0], a[1] + b[1]})));
        byExt.forEach((e, v) -> System.out.printf("%-7s %d files %4d bytes%n", e, v[0], v[1]));
        Path largest = files.stream().max(Comparator.comparingLong(Main::size)).orElseThrow();
        System.out.println("largest: " + root.relativize(largest) + " (" + size(largest) + " bytes)");

        try (Stream<Path> s = Files.walk(root)) { s.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); }
    }
}

Output Verified by compiling and running

(none)  1 files    3 bytes
java    2 files   41 bytes
md      2 files   31 bytes
largest: src/Util.java (28 bytes)

Checked IOException cannot leave a lambda, so size() wraps it in UncheckedIOException.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links