Java File Manager

Su Suriya Ravichandran Updated 18 Nov 2026
17 min read ·Lesson 301 of 306

A Java file manager is a command-line tool that lists folders, draws a folder tree, copies, moves and deletes files, searches by name or content, and reports disk usage. Building one is the best way to practise the java.nio.file API on real folders, because every operation must handle missing paths, existing targets and nested directories safely.

This project follows the Java Todo App and reuses its command-line style: each command runs, prints a result and exits with a status code. You build a FileInfo record, a FileManager class with listing, tree, copy, move, delete, search and usage methods, and finally fm.jar. All examples were run on JDK 21.


Describe Files With a FileInfo Record

Every listing needs the same three facts about an entry: its path, whether it is a folder, and its size. A record holds them, and a small helper turns raw byte counts into sizes people can read.

package com.gocourse.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/** A snapshot of one file or folder: its name, whether it is a folder, and its size in bytes. */
public record FileInfo(Path path, boolean directory, long size) {

    public static FileInfo of(Path path) throws IOException {
        boolean isDir = Files.isDirectory(path);
        return new FileInfo(path, isDir, isDir ? 0 : Files.size(path));
    }

    public String name() {
        return path.getFileName().toString();
    }

    /** 532 -> "532 B", 2048 -> "2.0 KB", 5_242_880 -> "5.0 MB". */
    public static String humanSize(long bytes) {
        if (bytes < 1024) return bytes + " B";
        String[] units = {"KB", "MB", "GB", "TB"};
        double value = bytes;
        int unit = -1;
        while (value >= 1024 && unit < units.length - 1) {
            value /= 1024;
            unit++;
        }
        return String.format("%.1f %s", value, units[unit]);
    }
}
package com.gocourse.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class SizeDemo {
    public static void main(String[] args) throws IOException {
        long[] samples = {0, 532, 1024, 2048, 1_536_000, 5_242_880, 3_221_225_472L};
        for (long bytes : samples) {
            System.out.printf("%,15d bytes = %s%n", bytes, FileInfo.humanSize(bytes));
        }

        Path notes = Files.writeString(Path.of("notes.txt"), "Buy milk\nCall plumber\n");
        FileInfo info = FileInfo.of(notes);
        System.out.println(info.name() + " is " + FileInfo.humanSize(info.size())
                + (info.directory() ? " (folder)" : " (file)"));
        Files.delete(notes);
    }
}
              0 bytes = 0 B
            532 bytes = 532 B
          1,024 bytes = 1.0 KB
          2,048 bytes = 2.0 KB
      1,536,000 bytes = 1.5 MB
      5,242,880 bytes = 5.0 MB
  3,221,225,472 bytes = 3.0 GB
notes.txt is 22 B (file)

How it works:

  • Files.isDirectory and Files.size read the information from the file system. A folder gets size 0 here; its real total is calculated later by the disk usage report.
  • humanSize divides by 1024 until the value is below 1024, moving one unit up each time. 3_221_225_472 bytes is divided three times and becomes 3.0 GB.
  • %.1f prints one decimal place, so every size has the same short format.
  • path.getFileName() returns only the last part of a path, such as notes.txt for docs/notes.txt.

List a Folder and Draw a Java Directory Tree

The FileManager class works inside one root folder. Every path the user types is resolved against that root, and any path that tries to leave it, such as ../.., is rejected. This is the most important safety rule in a file manager.

The listing and tree methods are shown first. The full class, with every method, is used in the later sections.

public class FileManager {
    /** Folders first, then names A-Z ignoring case. */
    static final Comparator<FileInfo> LISTING_ORDER = Comparator
            .comparing((FileInfo f) -> !f.directory())
            .thenComparing(f -> f.name().toLowerCase());

    private final Path root;

    public FileManager(Path root) {
        this.root = root.toAbsolutePath().normalize();
    }

    /** Resolves a user path and refuses anything that escapes the root, such as "../../etc". */
    public Path resolve(String userPath) {
        Path target = root.resolve(userPath).normalize();
        if (!target.startsWith(root)) {
            throw new IllegalArgumentException("Path is outside the managed folder: " + userPath);
        }
        return target;
    }

    public String relative(Path path) {
        String text = root.relativize(path).toString().replace('\\', '/');
        return text.isEmpty() ? "." : text;
    }

    public List<FileInfo> list(String folder) throws IOException {
        Path dir = resolve(folder);
        if (!Files.isDirectory(dir)) throw new IllegalArgumentException("Not a folder: " + folder);
        List<FileInfo> entries = new ArrayList<>();
        try (Stream<Path> children = Files.list(dir)) {
            for (Path child : (Iterable<Path>) children::iterator) {
                entries.add(FileInfo.of(child));
            }
        }
        entries.sort(LISTING_ORDER);
        return entries;
    }

    public List<String> tree(String folder, int maxDepth) throws IOException {
        List<String> lines = new ArrayList<>();
        Path dir = resolve(folder);
        lines.add((dir.equals(root) ? root.getFileName().toString() : relative(dir)) + "/");
        addTreeLines(dir, "", 1, maxDepth, lines);
        return lines;
    }

    private void addTreeLines(Path dir, String indent, int depth, int maxDepth, List<String> lines) throws IOException {
        List<FileInfo> children = list(relative(dir));
        for (int i = 0; i < children.size(); i++) {
            FileInfo child = children.get(i);
            boolean last = i == children.size() - 1;
            lines.add(indent + (last ? "└── " : "├── ") + child.name()
                    + (child.directory() ? "/" : "  (" + FileInfo.humanSize(child.size()) + ")"));
            if (child.directory() && depth < maxDepth) {
                addTreeLines(child.path(), indent + (last ? "    " : "│   "), depth + 1, maxDepth, lines);
            }
        }
    }
    // copy, move, delete, search and usage methods follow below
}

Every demo uses the same small sample folder, so the output is always the same:

package com.gocourse.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/** Builds the same small project folder for every demo, so the output is always identical. */
public class SampleFolder {
    public static Path create(String name) throws IOException {
        Path root = Path.of(name);
        removeIfPresent(root);
        Files.createDirectories(root.resolve("docs"));
        Files.createDirectories(root.resolve("src/app"));
        Files.createDirectories(root.resolve("photos"));
        Files.writeString(root.resolve("README.md"), "# Shop\nA small shop app.\nTODO: add screenshots\n");
        Files.writeString(root.resolve("docs/setup.txt"), "Install JDK 21\nRun the build\n");
        Files.writeString(root.resolve("docs/notes.txt"), "Meeting notes\ntodo: invoice template\n");
        Files.writeString(root.resolve("src/app/Main.java"), "class Main {\n    // TODO: read config\n}\n");
        Files.writeString(root.resolve("src/app/Cart.java"), "class Cart {\n    int items;\n}\n");
        Files.write(root.resolve("photos/beach.jpg"), new byte[245_760]);
        Files.write(root.resolve("photos/team.png"), new byte[1_258_291]);
        return root;
    }

    /** Deletes a leftover folder from an earlier run: deepest paths first. */
    static void removeIfPresent(Path folder) throws IOException {
        if (Files.notExists(folder)) return;
        try (var paths = Files.walk(folder)) {
            for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList()) Files.delete(p);
        }
    }
}
package com.gocourse.files;

import java.io.IOException;
import java.nio.file.Path;

public class ListDemo {
    public static void main(String[] args) throws IOException {
        Path root = SampleFolder.create("shop");
        FileManager fm = new FileManager(root);

        System.out.println("Contents of shop/:");
        for (FileInfo entry : fm.list(".")) {
            System.out.printf("  %-6s %-12s %10s%n", entry.directory() ? "<DIR>" : "",
                    entry.name(), entry.directory() ? "" : FileInfo.humanSize(entry.size()));
        }

        System.out.println();
        fm.tree(".", 3).forEach(System.out::println);

        System.out.println();
        System.out.println("Depth 1 only:");
        fm.tree(".", 1).forEach(System.out::println);

        try {
            fm.list("../..");
        } catch (IllegalArgumentException e) {
            System.out.println("\nBlocked: " + e.getMessage());
        }
    }
}
Contents of shop/:
  <DIR>  docs                   
  <DIR>  photos                 
  <DIR>  src                    
         README.md          47 B

shop/
├── docs/
│   ├── notes.txt  (37 B)
│   └── setup.txt  (29 B)
├── photos/
│   ├── beach.jpg  (240.0 KB)
│   └── team.png  (1.2 MB)
├── src/
│   └── app/
│       ├── Cart.java  (30 B)
│       └── Main.java  (40 B)
└── README.md  (47 B)

Depth 1 only:
shop/
├── docs/
├── photos/
├── src/
└── README.md  (47 B)

Blocked: Path is outside the managed folder: ../..

How it works:

  • root.resolve("../..").normalize() produces a path above the root. startsWith(root) is then false, so resolve throws before any file is touched.
  • Files.list returns a lazy Stream<Path> that holds an open directory handle. The try-with-resources block closes it, as explained in Java Directory Handling.
  • LISTING_ORDER sorts false before true, so !f.directory() puts folders first. Names are compared in lower case, so README.md sorts with the other r names.
  • addTreeLines calls itself for each sub-folder. The indent string grows by "│ " under a middle entry and by four spaces under the last one, which draws the tree lines.
  • maxDepth stops the recursion, so tree(".", 1) shows only the first level.

Copy, Move and Delete Files and Folders Safely

Files.copy and Files.delete work on one file or one empty folder. To copy or delete a whole folder, you walk it with Files.walkFileTree and a SimpleFileVisitor, which calls your methods for every folder and file it meets.

    /** Copies a file or a whole folder. Refuses to overwrite an existing target. */
    public int copy(String from, String to) throws IOException {
        Path source = resolve(from);
        Path target = resolve(to);
        if (Files.notExists(source)) throw new IllegalArgumentException("Not found: " + from);
        if (Files.exists(target)) throw new IllegalArgumentException("Already exists: " + to);
        if (target.startsWith(source)) throw new IllegalArgumentException("Cannot copy a folder into itself");

        int[] copied = {0};
        Files.walkFileTree(source, new SimpleFileVisitor<>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Files.createDirectories(target.resolve(source.relativize(dir)));
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.copy(file, target.resolve(source.relativize(file)), StandardCopyOption.COPY_ATTRIBUTES);
                copied[0]++;
                return FileVisitResult.CONTINUE;
            }
        });
        return copied[0];
    }

    /** Moves or renames a file or folder. Refuses to overwrite an existing target. */
    public void move(String from, String to) throws IOException {
        Path source = resolve(from);
        Path target = resolve(to);
        if (Files.notExists(source)) throw new IllegalArgumentException("Not found: " + from);
        if (Files.exists(target)) throw new IllegalArgumentException("Already exists: " + to);
        Files.createDirectories(target.getParent());
        Files.move(source, target);
    }

    /** Deletes a file, or a folder with everything inside it. Returns how many entries were removed. */
    public int delete(String userPath) throws IOException {
        Path target = resolve(userPath);
        if (target.equals(root)) throw new IllegalArgumentException("Refusing to delete the root folder");
        if (Files.notExists(target)) throw new IllegalArgumentException("Not found: " + userPath);

        int[] removed = {0};
        Files.walkFileTree(target, new SimpleFileVisitor<>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                removed[0]++;
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException error) throws IOException {
                if (error != null) throw error;
                Files.delete(dir); // the folder is empty now
                removed[0]++;
                return FileVisitResult.CONTINUE;
            }
        });
        return removed[0];
    }
package com.gocourse.files;

import java.io.IOException;
import java.nio.file.Path;

public class CopyMoveDeleteDemo {
    public static void main(String[] args) throws IOException {
        Path root = SampleFolder.create("shop");
        FileManager fm = new FileManager(root);

        System.out.println("Copied " + fm.copy("docs", "backup/docs") + " file(s) into backup/docs");
        System.out.println("Copied " + fm.copy("README.md", "backup/README.md") + " file(s)");

        fm.move("photos/team.png", "photos/2026/team-offsite.png");
        System.out.println("Moved photos/team.png -> photos/2026/team-offsite.png");

        String[][] badRequests = {
            {"copy", "docs", "backup/docs"},
            {"copy", "src", "src/app/src-copy"},
            {"move", "missing.txt", "x.txt"},
            {"delete", "."},
        };
        for (String[] request : badRequests) {
            try {
                switch (request[0]) {
                    case "copy" -> fm.copy(request[1], request[2]);
                    case "move" -> fm.move(request[1], request[2]);
                    case "delete" -> fm.delete(request[1]);
                }
            } catch (IllegalArgumentException e) {
                System.out.println(String.join(" ", request) + " -> " + e.getMessage());
            }
        }

        System.out.println("Deleted " + fm.delete("backup") + " entries from backup/");
        System.out.println();
        fm.tree(".", 3).forEach(System.out::println);
    }
}
Copied 2 file(s) into backup/docs
Copied 1 file(s)
Moved photos/team.png -> photos/2026/team-offsite.png
copy docs backup/docs -> Already exists: backup/docs
copy src src/app/src-copy -> Cannot copy a folder into itself
move missing.txt x.txt -> Not found: missing.txt
delete . -> Refusing to delete the root folder
Deleted 5 entries from backup/

shop/
├── docs/
│   ├── notes.txt  (37 B)
│   └── setup.txt  (29 B)
├── photos/
│   ├── 2026/
│   │   └── team-offsite.png  (1.2 MB)
│   └── beach.jpg  (240.0 KB)
├── src/
│   └── app/
│       ├── Cart.java  (30 B)
│       └── Main.java  (40 B)
└── README.md  (47 B)
Visitor methodCalledUsed here to
preVisitDirectoryBefore entering a folderCreate the same folder in the copy
visitFileFor each fileCopy or delete the file
postVisitDirectoryAfter leaving a folderDelete the folder, which is now empty
visitFileFailedWhen a file cannot be readNot overridden: the default rethrows the error

How it works:

  • source.relativize(dir) gives the path inside the source, such as docs/notes.txt becomes notes.txt. Resolving that against target places the copy in the same relative position.
  • COPY_ATTRIBUTES keeps the original last-modified time on the copies.
  • delete must remove the files before their folder. postVisitDirectory runs after all children are gone, so Files.delete(dir) succeeds. Deleting backup/ removed 5 entries: 3 files and 2 folders (backup/docs and backup).
  • move creates missing parent folders first, so photos/2026/ appeared automatically. Files.move on the same disk is a fast rename, not a copy.
  • The guards run before any change, so a rejected command leaves the folder untouched. The counters are int[] arrays because a local variable used inside an anonymous class must be effectively final, as covered in Java Anonymous Classes.

Search Files by Name, Content and Size in Java

A file manager also answers "where is it?" and "what is using the space?". Name search uses a glob pattern with PathMatcher, content search reads each matching file, and the usage report adds up file sizes with Files.walk.

    /** Finds files whose name matches a glob such as "*.java" or "report-*.{csv,txt}". */
    public List<Path> findByName(String glob) throws IOException {
        PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob);
        try (Stream<Path> found = Files.find(root, Integer.MAX_VALUE,
                (path, attrs) -> attrs.isRegularFile() && matcher.matches(path.getFileName()))) {
            return found.sorted().toList();
        }
    }

    /** Finds lines that contain the text, ignoring case. Returns "path:line: text" entries. */
    public List<String> grep(String text, String glob) throws IOException {
        String needle = text.toLowerCase();
        List<String> hits = new ArrayList<>();
        for (Path file : findByName(glob)) {
            List<String> lines;
            try {
                lines = Files.readAllLines(file);
            } catch (MalformedInputException e) {
                continue; // binary or non-UTF-8 file: skip it
            }
            for (int i = 0; i < lines.size(); i++) {
                if (lines.get(i).toLowerCase().contains(needle)) {
                    hits.add(relative(file) + ":" + (i + 1) + ": " + lines.get(i).strip());
                }
            }
        }
        return hits;
    }

    /** Size and file count of one top-level entry. */
    public record Usage(String name, long bytes, long files) { }

    /** Total size under each top-level entry of the folder, largest first. */
    public List<Usage> usage(String folder) throws IOException {
        List<Usage> result = new ArrayList<>();
        for (FileInfo entry : list(folder)) {
            try (Stream<Path> walk = Files.walk(entry.path())) {
                List<Path> files = walk.filter(Files::isRegularFile).toList();
                long bytes = files.stream().mapToLong(FileManager::sizeOf).sum();
                result.add(new Usage(entry.name() + (entry.directory() ? "/" : ""), bytes, files.size()));
            }
        }
        result.sort(Comparator.comparingLong(Usage::bytes).reversed());
        return result;
    }

    public List<FileInfo> largestFiles(int count) throws IOException {
        try (Stream<Path> files = Files.walk(root)) {
            return files.filter(Files::isRegularFile)
                    .map(p -> new FileInfo(p, false, sizeOf(p)))
                    .sorted(Comparator.comparingLong(FileInfo::size).reversed()
                            .thenComparing(f -> f.path().toString()))
                    .limit(count)
                    .toList();
        }
    }

    private static long sizeOf(Path file) {
        try {
            return Files.size(file);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
package com.gocourse.files;

import java.io.IOException;
import java.nio.file.Path;

public class SearchDemo {
    public static void main(String[] args) throws IOException {
        Path root = SampleFolder.create("shop");
        FileManager fm = new FileManager(root);

        for (String glob : new String[] {"*.java", "*.{jpg,png}", "*.txt", "*.pdf"}) {
            System.out.println(glob + " -> " + fm.findByName(glob).stream().map(fm::relative).toList());
        }

        System.out.println("\nLines containing \"todo\":");
        fm.grep("todo", "*").forEach(hit -> System.out.println("  " + hit));

        System.out.println("\nDisk usage of shop/:");
        long totalBytes = 0;
        for (FileManager.Usage u : fm.usage(".")) {
            System.out.printf("  %-11s %10s  %d file(s)%n", u.name(), FileInfo.humanSize(u.bytes()), u.files());
            totalBytes += u.bytes();
        }
        System.out.printf("  %-11s %10s%n", "total", FileInfo.humanSize(totalBytes));

        System.out.println("\nTwo largest files:");
        fm.largestFiles(2).forEach(f ->
                System.out.println("  " + FileInfo.humanSize(f.size()) + "  " + fm.relative(f.path())));
    }
}
*.java -> [src/app/Cart.java, src/app/Main.java]
*.{jpg,png} -> [photos/beach.jpg, photos/team.png]
*.txt -> [docs/notes.txt, docs/setup.txt]
*.pdf -> []

Lines containing "todo":
  README.md:3: TODO: add screenshots
  docs/notes.txt:2: todo: invoice template
  src/app/Main.java:2: // TODO: read config

Disk usage of shop/:
  photos/         1.4 MB  2 file(s)
  src/              70 B  2 file(s)
  docs/             66 B  2 file(s)
  README.md         47 B  1 file(s)
  total           1.4 MB

Two largest files:
  1.2 MB  photos/team.png
  240.0 KB  photos/beach.jpg
GlobMatches
*.javaAny name ending in .java
*.{jpg,png}Names ending in .jpg or .png
report-??.csvreport- plus exactly two characters, then .csv
*Every file name

How it works:

  • matcher.matches(path.getFileName()) tests only the file name. Matching the full path with *.java would fail, because * in a glob does not cross folder separators.
  • Files.find walks the whole tree and keeps paths for which the lambda returns true. Its attrs parameter avoids a second disk call to check isRegularFile.
  • grep lowers both the line and the search text, so TODO, todo and ToDo all match. Files.readAllLines throws MalformedInputException for files that are not valid UTF-8, and the loop simply skips those.
  • Files.size throws a checked IOException, which a stream lambda cannot throw. sizeOf wraps it in UncheckedIOException, a common pattern with the Java Files API.
  • largestFiles sorts by size with reversed(), then by path to break ties, and limit(count) keeps the top results.

Build the Java File Manager Command-Line Tool

FileManagerApp maps commands such as ls, cp and grep to FileManager methods. Like the todo app, run returns an exit code instead of calling System.exit, so it can be tested.

package com.gocourse.files;

import java.io.IOException;
import java.nio.file.Path;

/** Command-line file manager: java -jar fm.jar <command> [arguments] */
public class FileManagerApp {
    public static void main(String[] args) {
        Path root = Path.of(System.getProperty("fm.root", "."));
        try {
            System.exit(run(args, new FileManager(root)));
        } catch (IOException e) {
            System.err.println("I/O error: " + e.getMessage());
            System.exit(2);
        }
    }

    /** Runs one command. Exit codes: 0 = success, 1 = user error, 2 = I/O error (thrown). */
    static int run(String[] args, FileManager fm) throws IOException {
        String command = args.length == 0 ? "help" : args[0];
        try {
            switch (command) {
                case "ls" -> fm.list(arg(args, 1, ".")).forEach(f -> System.out.printf("%-6s %-22s %10s%n",
                        f.directory() ? "<DIR>" : "", f.name(), f.directory() ? "" : FileInfo.humanSize(f.size())));
                case "tree" -> fm.tree(arg(args, 1, "."), Integer.parseInt(arg(args, 2, "10")))
                        .forEach(System.out::println);
                case "cp" -> System.out.println("Copied " + fm.copy(need(args, 1), need(args, 2)) + " file(s)");
                case "mv" -> {
                    fm.move(need(args, 1), need(args, 2));
                    System.out.println("Moved " + args[1] + " -> " + args[2]);
                }
                case "rm" -> System.out.println("Deleted " + fm.delete(need(args, 1)) + " entries");
                case "find" -> fm.findByName(need(args, 1)).forEach(p -> System.out.println(fm.relative(p)));
                case "grep" -> fm.grep(need(args, 1), arg(args, 2, "*")).forEach(System.out::println);
                case "du" -> fm.usage(arg(args, 1, ".")).forEach(u -> System.out.printf("%10s  %-22s %d file(s)%n",
                        FileInfo.humanSize(u.bytes()), u.name(), u.files()));
                case "big" -> fm.largestFiles(Integer.parseInt(arg(args, 1, "5"))).forEach(f ->
                        System.out.printf("%10s  %s%n", FileInfo.humanSize(f.size()), fm.relative(f.path())));
                default -> {
                    System.out.println("""
                            Commands:
                              ls [folder]            list a folder
                              tree [folder] [depth]  show a folder tree
                              cp <from> <to>         copy a file or folder
                              mv <from> <to>         move or rename
                              rm <path>              delete a file or folder
                              find <glob>            find files by name, e.g. "*.java"
                              grep <text> [glob]     find lines containing text
                              du [folder]            size of each entry
                              big [count]            largest files""");
                    return command.equals("help") ? 0 : 1;
                }
            }
            return 0;
        } catch (IllegalArgumentException e) { // also catches NumberFormatException
            System.out.println("Error: " + e.getMessage());
            return 1;
        }
    }

    private static String arg(String[] args, int index, String fallback) {
        return args.length > index ? args[index] : fallback;
    }

    private static String need(String[] args, int index) {
        if (args.length <= index) throw new IllegalArgumentException("Missing argument. Run 'help' for usage");
        return args[index];
    }
}

How it works:

  • The root folder comes from the system property fm.root and defaults to the current folder (.), so -Dfm.root=shop limits every command to shop/.
  • arg returns an optional argument or a default, and need throws a clear error when a required argument is missing.
  • NumberFormatException is a subclass of IllegalArgumentException, so tree . abc is reported as a user error with exit code 1.
  • help prints the command list with exit code 0, while an unknown command prints the same list with exit code 1.

Real-World Example: Organise a Project Folder With fm.jar

file-manager/
└── src/
    └── com/
        └── gocourse/
            └── files/
                ├── FileInfo.java
                ├── FileManager.java
                └── FileManagerApp.java
cd file-manager
javac -d out src/com/gocourse/files/*.java
jar --create --file fm.jar --main-class com.gocourse.files.FileManagerApp -C out .

# a short command for the terminal (Linux/macOS), limited to the shop/ folder
alias fm='java -Dfm.root=shop -jar fm.jar'

A session on the sample shop/ folder. Glob patterns are quoted so the shell passes them to Java unchanged.

$ fm tree
shop/
├── docs/
│   ├── notes.txt  (37 B)
│   └── setup.txt  (29 B)
├── photos/
│   ├── beach.jpg  (240.0 KB)
│   └── team.png  (1.2 MB)
├── src/
│   └── app/
│       ├── Cart.java  (30 B)
│       └── Main.java  (40 B)
└── README.md  (47 B)
$ fm find '*.java'
src/app/Cart.java
src/app/Main.java
$ fm grep todo
README.md:3: TODO: add screenshots
docs/notes.txt:2: todo: invoice template
src/app/Main.java:2: // TODO: read config
$ fm cp docs archive/2026/docs
Copied 2 file(s)
$ fm mv photos/beach.jpg photos/holidays/goa-beach.jpg
Moved photos/beach.jpg -> photos/holidays/goa-beach.jpg
$ fm rm src/app/Cart.java
Deleted 1 entries
$ fm cp README.md archive/2026/docs
Error: Already exists: archive/2026/docs
$ echo $?
1
$ fm rm ../shop
Error: Refusing to delete the root folder
$ fm mv a
Error: Missing argument. Run 'help' for usage
$ fm du
    1.4 MB  photos/                2 file(s)
      66 B  archive/               2 file(s)
      66 B  docs/                  2 file(s)
      47 B  README.md              1 file(s)
      40 B  src/                   1 file(s)
$ fm big 3
    1.2 MB  photos/team.png
  240.0 KB  photos/holidays/goa-beach.jpg
      47 B  README.md
$ fm tree . 2
shop/
├── archive/
│   └── 2026/
├── docs/
│   ├── notes.txt  (37 B)
│   └── setup.txt  (29 B)
├── photos/
│   ├── holidays/
│   └── team.png  (1.2 MB)
├── src/
│   └── app/
└── README.md  (47 B)

How it works:

  1. Overview first. tree shows the whole project, and find and grep locate the Java sources and every TODO note without opening an editor.
  2. Organising. cp backed up docs/ into a new archive/2026/ folder, and mv renamed the beach photo while creating photos/holidays/ on the way.
  3. Safe by default. Copying onto an existing folder, deleting the root (../shop normalises to the root itself) and a missing argument all stop with exit code 1 and change nothing.
  4. Space report. du shows that photos/ holds almost all the bytes, and big 3 names the exact files to compress or move.
  5. Depth control. tree . 2 stops after two levels, which keeps the output short for large projects.

The next project, the Java Quiz App, loads questions from a file, shuffles them and scores the player's answers.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java File Manager and get answers drawn from it.

Signed-in readers only.