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

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 |
|
Large, line-oriented text |
|
Binary data | Buffered byte streams |
Straight whole-file 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:
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:
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:
student,score
Asha,78
Ravi,91
Meera,85The 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:
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 |
|
|
|
|---|---|---|---|
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:
Students=3
Average=84.67
Top=Ravi:91split(",", -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.

Copy binary data without stale buffer bytes
Create a ten-byte payload, then copy only the bytes returned by each read:
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).

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 exactlyn.Forgetting
APPENDcan replace content. Choose open options deliberately.Joining path strings invites separator mistakes. Use
Path.ofandresolve.Checking before creating is race-prone. Use
CREATE_NEWand 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
PathplusFilesfor 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.
Keep learning
File Handling in Python: Read, Write, Append, CSV and Binary Examples
Learn a reliable file-handling workflow through one scores file, then apply it to cursor control, append mode, CSV quoting, binary records and common errors.
File Handling in C++: Read, Write, Append and Seek with Examples
Learn how C++ file streams work through connected text and binary examples, from safe record parsing to appending data and updating a fixed record.
File Handling in C: fopen, Read, Write, Append and Seek with Runnable Examples
Build safe C file workflows with text and binary examples. Write records, total them, append data, seek by byte offset, and handle failures.
Node.js File System Tutorial: Read, Write and Manage Files with Runnable Examples
Build one path-safe Node.js lab that reads attempt records, calculates accuracy, creates an output directory, writes a JSON summary, and appends an audit log.





