File Handling in Java: Read, Write, Append and Copy Files Safely

Learn how Java's Path, Files, character streams and byte streams fit together. Build a score file, aggregate its rows, and copy binary data safely.

KnowledgeGate Team

Exam prep & CS education

Updated 2 Dec 20265 min read
File Handling in Java: Read, Write, Append and Copy Files Safely

A Java programme can compile and still lose data, duplicate rows, corrupt a binary copy, or fail to release a resource. The usual cause is a wrong API, open option, charset, or resource-lifetime rule. A score file exposes these choices, and a byte-copy trace exposes the partial-read rule.

Build the Java file-handling mental model

Start with roles, not syntax. Path identifies a location such as data/scores.csv. Files creates directories and handles common file operations. Reader and Writer process characters, while InputStream and OutputStream process raw bytes. From the programme's viewpoint, input enters the programme and output leaves it.

Task

Suitable API

Small UTF-8 text

Files.readString or Files.writeString

Large, line-oriented text

BufferedReader or BufferedWriter

Binary data

Buffered byte streams

Straight whole-file copy

Files.copy

Buffering reduces repeated low-level I/O calls. It does not turn text into binary or binary into text.

The broader Java NIO and File I/O: Paths, Channels and Buffer States treatment covers FileChannel, ByteBuffer, copying, and moving. The two worked traces that follow cover UTF-8 text writing and aggregation, then the partial-read buffer rule.

Create paths through the API, not by joining strings:

java
Path dataDir = Path.of("data");
Files.createDirectories(dataDir);
Path scores = dataDir.resolve("scores.csv");

The Coding and Skills category places this topic within a wider programming track. If you know file handling in C, do not transfer its FILE * objects and mode strings mechanically. Java uses resource objects, open options, and exceptions differently.

Write, overwrite and append one UTF-8 text file

This runnable example creates the directory, writes 30 bytes, appends 9 bytes, and reports the final size:

java
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class WriteScores {
    public static void main(String[] args) throws Exception {
        Path dataDir = Path.of("data");
        Files.createDirectories(dataDir);
        Path scores = dataDir.resolve("scores.csv");

        String initial = "student,score\nAsha,78\nRavi,91\n";
        Files.writeString(scores, initial, StandardCharsets.UTF_8,
                StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING,
                StandardOpenOption.WRITE);

        Files.writeString(scores, "Meera,85\n", StandardCharsets.UTF_8,
                StandardOpenOption.APPEND);
        System.out.println(Files.size(scores)); // 39
    }
}

TRUNCATE_EXISTING replaces old content, while APPEND writes after it. Use CREATE_NEW when an existing file must cause failure. The resulting file is exactly 39 bytes because every character in this fixture occupies one UTF-8 byte:

Code
student,score
Asha,78
Ravi,91
Meera,85

The ending \n matters. Appending Meera,85 without it can make the next record join the same line. Use System.lineSeparator() instead when the file must follow the host platform's line-ending convention.

Read the rows and compute a result

For an unknown-size file, read one line at a time and keep only the current line plus four accumulator values:

java
int count = 0, sum = 0;
String topName = "";
int topScore = Integer.MIN_VALUE;

try (BufferedReader reader = Files.newBufferedReader(scores, StandardCharsets.UTF_8)) {
    String header = reader.readLine();
    if (!"student,score".equals(header)) {
        throw new IOException("Unexpected header in " + scores);
    }

    for (String line; (line = reader.readLine()) != null; ) {
        String[] fields = line.split(",", -1);
        String name = fields[0];
        int score = Integer.parseInt(fields[1]);
        count++;
        sum += score;
        if (score > topScore) {
            topName = name;
            topScore = score;
        }
    }
}

System.out.printf(Locale.ROOT,
        "Students=%d%nAverage=%.2f%nTop=%s:%d%n",
        count, sum / (double) count, topName, topScore);

The accumulator trace is:

Step

count

sum

top

Start

0

0

none

After Asha, 78

1

78

Asha:78

After Ravi, 91

2

169

Ravi:91

After Meera, 85

3

254

Ravi:91

Therefore 254 / 3.0 = 84.666..., which prints as:

Code
Students=3
Average=84.67
Top=Ravi:91

split(",", -1) preserves empty trailing fields, but it is suitable only for this controlled fixture. It is not a general CSV parser for quoted commas. Collecting records in a List can be useful, but the streaming accumulator uses less memory than readAllLines when file size is unknown.

Flow diagram traces UTF-8 score-file parsing from header skip through three rows to counts, sum, top score, average, and printed output.

Copy binary data without stale buffer bytes

Create a ten-byte payload, then copy only the bytes returned by each read:

java
Path source = dataDir.resolve("payload.bin");
Path copy = dataDir.resolve("payload-copy.bin");
Files.write(source, new byte[]{10, 20, 30, 40, 50, 60, 70, 80, 90, 100});

try (InputStream in = new BufferedInputStream(Files.newInputStream(source));
     OutputStream out = new BufferedOutputStream(Files.newOutputStream(copy))) {
    byte[] buffer = new byte[4];
    int n;
    while ((n = in.read(buffer)) != -1) {
        out.write(buffer, 0, n);
    }
}

The reads return n=4, n=4, n=2, then n=-1. On the third read, the buffer can contain [90,100,70,80]; only the first two slots are new. Writing n bytes gives 4 + 4 + 2 = 10. Writing the full buffer each time would add stale 70,80 and produce 12 bytes.

Verify Files.size(copy) == 10 and Arrays.equals(Files.readAllBytes(source), Files.readAllBytes(copy)) == true. Whole-file reads are reasonable only because this fixture is ten bytes. Arbitrary bytes must not pass through a Reader, which may change or reject them. Images and archives remain byte-oriented. When no per-chunk work is needed, use Files.copy(source, copy, REPLACE_EXISTING).

Byte-buffer diagram shows three reads of a ten-byte payload, writes only n bytes on the final partial read, and excludes stale trailing values.

Let try-with-resources own cleanup

Resources declared inside try (...) close when the block finishes, including when parsing or writing throws. In the copy example, input is declared first and output second.

Handle specific failures at a useful boundary. Reading data/missing.csv can raise NoSuchFileException. After the 39-byte score file exists, Files.writeString(scores, "x", UTF_8, CREATE_NEW) can raise FileAlreadyExistsException. Add the path and intended operation to an error message, preserve the original exception as the cause when wrapping, then either recover deliberately or stop. Never swallow a broad exception or silently ignore a close failure.

Common file-handling traps and safer replacements

  • Implicit charset makes text machine-dependent. Pass UTF_8.

  • Whole-file reads on unbounded input can exhaust memory. Stream lines or chunks.

  • Assuming read(buffer) fills every slot writes stale bytes. Write exactly n.

  • Forgetting APPEND can replace content. Choose open options deliberately.

  • Joining path strings invites separator mistakes. Use Path.of and resolve.

  • Checking before creating is race-prone. Use CREATE_NEW and handle its exception.

  • Happy-path tests miss empty files, missing headers, blank scores, and malformed integers. Test them explicitly.

For these fixtures, assert 39 bytes, compare the three output lines exactly, and assert that source and copied byte arrays are equal. Run the writer twice too. Its initial truncating write should restore the same four lines, not duplicate them.

The short version and what to practise next

Assessments may ask you to predict overwrite versus append output, choose character or byte streams, explain checked I/O failures, spot missing cleanup, or replace out.write(buffer) with out.write(buffer, 0, n).

  • Use Path plus Files for common operations.

  • Specify UTF-8 for text.

  • Buffer unknown-size sequential input.

  • Use try-with-resources and honour the actual read count.

Now append Kabir,88\n. Predict the new size: 39 + 9 = 48 bytes. Recompute count = 4, sum = 254 + 88 = 342, average = 342 / 4 = 85.50, while top = Ravi:91 remains unchanged. For full language coverage, use the Java Programming course as your next structured step. For interview-focused problem solving in Java, continue with Data Structures and Algorithms Using Java.