0Pricing
Java Academy · Lesson

Files Utility: Read, Write, Copy, Move

Use Files.readString, writeString, copy, move, delete for common file operations.

Files Utility: Read, Write, Copy, Move is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Files Class

The java.nio.file.Files class provides static utility methods for reading, writing, copying, moving, and querying files. It replaces verbose FileInputStream/FileOutputStream boilerplate.

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

Path file = Path.of("example.txt");
// All Files methods throw IOException — handle or propagate

Reading Files

Modern methods for reading a file's entire contents:

Path path = Path.of("notes.txt");

// Read as a single String (Java 11+)
String content = Files.readString(path);
System.out.println(content);

// Read as List of lines
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);

// Read as byte array
byte[] bytes = Files.readAllBytes(path);

Writing Files

Write a String or collection of lines to a file in one call:

Path out = Path.of("output.txt");

// Write a String (overwrites by default)
Files.writeString(out, "Hello, NIO.2!");

// Write with StandardOpenOption.APPEND
Files.writeString(out, "\nAppended line", StandardOpenOption.APPEND);

// Write lines
List<String> lines = List.of("line1", "line2", "line3");
Files.write(out, lines);

Checking File Properties

Query file metadata without opening the file:

Path path = Path.of("data.txt");

System.out.println(Files.exists(path));       // true/false
System.out.println(Files.isRegularFile(path)); // true if not dir
System.out.println(Files.isDirectory(path));   // true if dir
System.out.println(Files.isReadable(path));    // readable?
System.out.println(Files.size(path));          // bytes
System.out.println(Files.getLastModifiedTime(path));

Copying Files

Files.copy(source, target) copies a file. Use StandardCopyOption to control behavior:

Path src = Path.of("original.txt");
Path dst = Path.of("backup.txt");

// Throws if destination exists (default)
Files.copy(src, dst);

// Overwrite if exists:
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);

// Copy preserving file timestamps:
Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES);

Moving and Renaming Files

Files.move() moves or renames a file. Atomic move is possible with ATOMIC_MOVE:

Path from = Path.of("temp.txt");
Path to   = Path.of("archive/report_2024.txt");

Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);

// Rename in same directory:
Path renamed = from.resolveSibling("new_name.txt");
Files.move(from, renamed, StandardCopyOption.REPLACE_EXISTING);

Deleting Files

Two delete methods — one throws if not found, one doesn't:

Path file = Path.of("temp.txt");

// Throws NoSuchFileException if file doesn't exist:
Files.delete(file);

// Returns false if file didn't exist (no exception):
boolean deleted = Files.deleteIfExists(file);
System.out.println("Deleted: " + deleted);

Creating Directories

Create directories, including all intermediate ones:

Path dir = Path.of("output/reports/2024");

// Creates all missing intermediate directories:
Files.createDirectories(dir);

// Creates a single directory (fails if parent missing):
Files.createDirectory(Path.of("output/reports/2025"));

Temporary Files and Directories

Create temp files safely — the JVM can clean them up:

// Temp file in default temp directory
Path tmp = Files.createTempFile("prefix_", ".txt");
Files.writeString(tmp, "temp data");
System.out.println(tmp); // something like /tmp/prefix_12345.txt

// Temp directory
Path tmpDir = Files.createTempDirectory("work_");
System.out.println(tmpDir);

Streaming Lines with Files.lines

Files.lines() returns a lazy Stream<String> — better than readAllLines for large files since it doesn't load everything into memory:

try (var stream = Files.lines(Path.of("large.log"))) {
    long errorCount = stream
        .filter(l -> l.contains("ERROR"))
        .count();
    System.out.println("Errors: " + errorCount);
} // stream (and underlying reader) closed automatically

Reading from Classpath Resources

Combine with getClass().getResourceAsStream() and NIO copying for resource loading:

try (var in = getClass().getResourceAsStream("/config.json")) {
    Path tmp = Files.createTempFile("config", ".json");
    Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
    String json = Files.readString(tmp);
    System.out.println(json);
}

Quick Check

Which method should you use to read a large log file without loading all lines into memory simultaneously?

Recap: Files Utility

Key takeaways:

  • Files.readString/readAllLines/readAllBytes — read whole file
  • Files.writeString/write — write string or lines
  • Files.copy/move with StandardCopyOption — copy/rename/move
  • Files.delete/deleteIfExists — safe deletion
  • Files.lines — lazy stream for large files (use try-with-resources)

Frequently asked questions

Is the “Files Utility: Read, Write, Copy, Move” lesson free?

Yes — the full text of “Files Utility: Read, Write, Copy, Move” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Files Utility: Read, Write, Copy, Move”?

Use Files.readString, writeString, copy, move, delete for common file operations. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Files Utility: Read, Write, Copy, Move” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Path: Representing File Locations
  2. Files Utility: Read, Write, Copy, Move
  3. Walking Directory Trees with Files.walk
  4. WatchService: Monitoring File Changes
← Back to Java Academy