Skip to content
Tutorials Center
My learning

Topics

Lesson 197 of 201 ยท Practice and Review

File and Directory Programs in Java

Practice Java file handling with runnable programs - create, rename, copy and append files, compare paths, grep, measure and delete folders, search trees and read ZIP entries.

Reading about Files and Path is one thing; being able to write a small file utility from memory is another. This lesson is a set of short, complete programs for the jobs people actually ask for: create, rename, copy and append files, compare paths, search inside files and folders, add up a directory's size, delete a whole tree and peek into a ZIP archive.

Every program builds its own scratch files in a temporary directory and cleans up after itself, so you can run them as many times as you like. The API behind them is explained in Files and Paths, Directories and Walking Trees and Compression; here the goal is practice.

The programs use the modern java.nio.file API. It reports problems with specific exceptions (FileAlreadyExistsException, NoSuchFileException) and works the same on every platform. The old java.io.File class appears only where it has no direct replacement, such as setReadOnly.

Create, append, rename, copy

The four everyday operations each map to one call. writeString creates or replaces; adding StandardOpenOption.APPEND adds to the end. Files.move is both "rename" and "move to another folder". Files.copy refuses to overwrite unless you say REPLACE_EXISTING, which protects you from silent data loss.

Files.mismatch(a, b) returns -1 when two files have identical content, otherwise the position of the first different byte, which makes it a one-line "are these files equal?" test.

Java Create, append, rename, copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three details are worth noticing in the output:

  • Read-only is a file attribute. setReadOnly() flips it, and Files.isWritable reflects it. (On a Unix system as the file owner it affects the write bit; as root, writes may still succeed.)
  • Comparing paths has three levels. equals compares the path text, so data/../data/a.txt and data/a.txt differ. normalize() removes the .. segments. Files.isSameFile asks the file system, so it is the only one that detects "same file reached by two routes", and it needs both paths to exist.
  • Clean up in the right order. A directory must be empty before Files.delete removes it.

Searching and measuring a tree

Files.walk(root) gives a lazy Stream<Path> of everything below a folder. That stream holds open directory handles, so always put it in a try-with-resources block (see try-with-resources). Once you have the stream, every question is a normal stream pipeline: filter, map, sum.

This program does five jobs on a small project tree: grep one file with line numbers, total the size of all regular files, find files by extension, grep the whole tree and finally delete everything.

Java Grep, size, search, recursive delete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Points to remember:

  • Recursive create is Files.createDirectories; unlike createDirectory it creates missing parents and does nothing if the folder already exists.
  • Directory size is "sum of the sizes of the regular files". Filter with Files::isRegularFile, or the folders themselves are counted too.
  • Recursive delete must delete children before parents. walkFileTree with a SimpleFileVisitor expresses that directly: delete files in visitFile and the now-empty directory in postVisitDirectory, and errors can be handled per file.
  • Current directory. Path.of("").toAbsolutePath() is the portable way to ask where relative paths resolve; System.getProperty("user.dir") agrees with it.
  • On Windows relativize prints backslashes; the output above comes from a Linux runner.

Reading ZIP entries and temp files

A ZIP archive is a list of entries, each with a name, an uncompressed size and a compressed size. ZipFile reads the central directory at the end of the archive, so you can list the entries and open any single one without scanning the whole file. Names ending in / are directory entries.

Java Create a ZIP, then read its entries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same program shows the two kinds of temporary file: Files.createTempFile(prefix, suffix) creates a uniquely named empty file in the system temp folder, and deleteOnExit() asks the JVM to remove it when the program ends. For long-running servers, delete temporary files yourself in a finally block instead of waiting for exit.

When you extract ZIP entries to disk, never trust the entry name. A name like ../../etc/cron.d/job writes outside your target folder ("zip slip"). Resolve the name against the target directory, normalize() it and check that it still startsWith the target. Compression shows the full safe version.

Exercises

  1. Write long countLines(Path file) and use it to print the line count of every .java file under a folder, largest first.
  2. Write a copyTree(Path from, Path to) using walkFileTree, then verify every file with Files.mismatch.
  3. Write deleteOlderThan(Path dir, Duration age) that deletes regular files whose Files.getLastModifiedTime is older than the cutoff.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call tells you whether two different path strings point to the same existing file?

    equals and compareTo look only at the path text, and normalize only removes dot segments. Files.isSameFile asks the file system, so it also sees through links and different routes to one file.
  2. 2. Why must the stream returned by Files.walk be closed?

    Files.walk and Files.list keep directories open while the stream is alive. Use try-with-resources so they are released even when the pipeline throws.
  3. 3. In a recursive delete with walkFileTree, where is each directory deleted?

    A directory has to be empty before it can be deleted. postVisitDirectory runs after all its children were visited and deleted.
  4. 4. What does Files.copy(source, target) do when target already exists?

    The default is to refuse, so a careless copy cannot destroy data. Pass StandardCopyOption.REPLACE_EXISTING when you really want to replace.

Summary

  • Create and append with Files.writeString (plus APPEND); rename or move with Files.move; copy with Files.copy, which refuses to overwrite by default.
  • Files.mismatch compares two files by content; Files.isSameFile compares by identity; Path.equals compares text.
  • Files.walk plus stream operations answers most "find / grep / total size" questions; always close the stream.
  • Delete a tree children first, with walkFileTree and postVisitDirectory.
  • ZipFile lists and opens single entries quickly; never trust entry names when extracting.

Next: Java Practice Exercises, where you'll solve graded problems yourself before peeking at the solutions.