Java basics series: 1. JVM and JDK · 2. Hello World and the three kinds of errors · 3. Variables and types · 4. Operators and branching · 5. Loops and methods · 6. Arrays and strings · 7. Console and text files · 8. Byte streams and serialization
A backend reads and writes text files everywhere: CSV imports, report exports, config files, log processing. After this post you can print and read the console properly, read and write text files without losing data or leaking file descriptors, and pick the right API for the file size. Read arrays and strings first; byte streams, buffering and serialization are in the next post: byte streams and serialization.
1. Reading and writing text
Key idea: on the console you print with System.out.printf and read with Scanner; for text files you read with Scanner/BufferedReader and write with PrintWriter/BufferedWriter. The two easiest mistakes: the nextLine trap and overwriting by default.
Writing to the console
| Method | What it does |
|---|---|
System.out.print(x) |
prints without a newline |
System.out.println(x) |
prints, then a newline |
System.out.printf(format, args...) |
prints using a format string |
System.out.printf("%-10s|%8.2f|%05d%n", "Coffee", 35.5, 42);
// Coffee | 35.50|00042
Common specifiers:
%dinteger,%f/%.2ffloating point,%sstring,%bboolean,%cchar.%nthe platform’s line separator (prefer it to\n).%-10sleft-aligned in 10 columns,%,dwith thousands separators.%fprints 6 decimal places by default (3.141593); for fewer, say so, e.g.%.3f.
String.format and "...".formatted(...) use the same syntax but return the string instead of printing it. On a backend, don’t log with System.out; use a logger (SLF4J + Logback) for log levels, async appenders, JSON output and trace ids.
Reading from the console with Scanner
Scanner in = new Scanner(System.in);
String word = in.next(); // one "word", stops at whitespace
int age = in.nextInt(); // likewise: nextByte, nextShort, nextLong, nextFloat, nextDouble, nextBoolean
String line = in.nextLine(); // the rest of the line, up to the line break
Reading a file
Scanner can read a whole file too, token by token (words separated by whitespace):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
try (Scanner sc = new Scanner(new File("data.txt"))) { // the slide forgets the new before File
while (sc.hasNext()) { // is there another token?
System.out.println(sc.next());
}
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
}
Writing a file
PrintWriter has the same print, println and printf as System.out:
import java.io.PrintWriter;
try (PrintWriter out = new PrintWriter("report.txt")) {
out.println("Report");
out.print("Total: ");
out.printf("%d%n", 123);
} // try-with-resources calls close() for you, even if an exception is thrown
FileReader, FileWriter and BufferedWriter
These are the “original” java.io classes for text files, still common in older code and in course material. Four things to remember:
- They overwrite by default.
FileWriter,PrintWriterandFiles.writeall create the file or overwrite it. Forget that and the old data is gone; to append, passtrueorStandardOpenOption.APPEND. read()returns anint, not achar, so there’s room for-1to signal the end of the data.- Unbuffered is very slow. Reading raw character by character makes a call down to the OS each time (the details are in the byte streams post). In practice you read lines with
BufferedReader/Files.newBufferedReader, write withBufferedWriter, and wrap aPrintWriteraround it when you needprintf. - The charset parameter of
FileReader/FileWriteronly exists since Java 11.
Sample code: FileReader, FileWriter overwrite vs append, Files.write
try (FileReader reader = new FileReader("lines.txt", StandardCharsets.UTF_8)) { // the charset parameter needs Java 11+
int c;
while ((c = reader.read()) != -1) { // read() returns one character as an int, -1 at end of file
System.out.print((char) c);
}
}
try (FileWriter w = new FileWriter("log.txt")) { w.write("a\n"); } // creates the file or OVERWRITES it
try (FileWriter w = new FileWriter("log.txt", true)) { w.write("b\n"); } // true = append to the end
try (BufferedWriter w = new BufferedWriter(new FileWriter("log.txt", true))) {
w.write("c");
w.newLine(); // the OS-specific line separator
}
// log.txt now has 3 lines: a, b, c
Files.write(Path.of("lines.txt"), List.of("x", "y")); // overwrite
Files.write(Path.of("lines.txt"), List.of("z"), StandardOpenOption.APPEND); // append
2. try-with-resources everywhere
Key idea: anything holding an OS resource must be closed where it was opened, with try-with-resources. It closes even when an exception is thrown, and it doesn’t lose the original error.
The resource here is a file descriptor (FD, the number the OS hands out for each open file or socket) or a socket. What needs closing: every stream, reader, writer, file-backed Scanner, connection, and the Stream from Files.lines, Files.list and Files.walk. Only Files.readAllLines, readString and readAllBytes close themselves, because they read everything in one go.
- Several resources are declared separated by
;and closed in reverse order of opening. - Errors aren’t overwritten. If the
trybody throws andclose()throws too, theclose()exception is attached to the main one as suppressed (e.getSuppressed()). With the oldfinally { in.close(); }style, an exception infinallyreplaces the original one.
Forget to close and the first thing to run out is usually FDs: the process hits its ulimit -n and every new file or socket fails with “Too many open files”. How to reproduce it, count a JVM’s FDs through /proc/<pid>/fd and find the leak is in I/O models: blocking, epoll and file descriptors.
Two-resource example and the Java 9 syntax
try (InputStream in = new BufferedInputStream(new FileInputStream("in.mp3"));
OutputStream out = new BufferedOutputStream(new FileOutputStream("copy.mp3"))) {
in.transferTo(out);
} // closed in reverse order: out first, then in; out gets flushed on close
Since Java 9 you can reuse an existing effectively final variable (one never reassigned after initialization): try (in) { ... }.
3. java.nio.file.Files: the modern default
Key idea: new code should use Path + Files (NIO.2, Java 7) instead of java.io.File: errors say why, UTF-8 is the default, and almost every common operation is built in. Pick how to read based on file size.
java.io.File dates back to Java 1.0: many of its methods return false instead of saying what went wrong (file.delete() fails and you never learn why). Files throws informative exceptions (NoSuchFileException, AccessDeniedException).
flowchart LR
A["Need to read a text file"] --> B{"Small file, a few MB?"}
B -->|yes| C["Files.readString / readAllLines"]
B -->|no| D{"Need per-line control?"}
D -->|no| E["Files.lines in try-with-resources"]
D -->|yes| F["Files.newBufferedReader + readLine"]
Writing safely while other processes may be reading: write to a temp file in the same directory, then rename it in one step with ATOMIC_MOVE. Readers see either the old file or the complete new one, never a half-written file.
Path target = Path.of("report.txt");
Path tmp = Files.createTempFile(target.toAbsolutePath().getParent(), "report", ".tmp");
Files.writeString(tmp, content);
Files.move(tmp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
When do you still use InputStream/Reader directly? When the data doesn’t come from a file: an HTTP body, a socket, a resource inside a jar (getResourceAsStream), decompressed data. Files hands them out when needed, too: Files.newInputStream, Files.newBufferedReader.
Everyday Files operations: read, write, copy, create and walk directories
Path in = Path.of("data", "students.csv");
String all = Files.readString(in); // small file, UTF-8 by default
byte[] bytes = Files.readAllBytes(Path.of("logo.png")); // small binary file
long size = Files.size(in); // the real size
boolean exists = Files.exists(in);
try (BufferedReader r = Files.newBufferedReader(in); // large file: line by line, buffered
BufferedWriter w = Files.newBufferedWriter(Path.of("report.txt"))) {
String line;
while ((line = r.readLine()) != null) {
w.write(line.toUpperCase());
w.newLine();
}
}
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Files.createDirectories(Path.of("out", "2026", "11")); // creates the whole directory tree
try (Stream<Path> files = Files.walk(Path.of("logs"))) { // walks a directory tree; must be closed
files.filter(p -> p.toString().endsWith(".log")).forEach(System.out::println);
}
Exercises
Each prompt is a short paraphrase. All solutions were run on JDK 21.
1. Write a 3D array to a text file.
static void write3D(int[][][] cube, Path file) throws IOException {
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(file))) {
for (int layer = 0; layer < cube.length; layer++) {
out.printf("Layer %d%n", layer);
for (int[] row : cube[layer]) {
StringJoiner line = new StringJoiner(" ");
for (int x : row) line.add(String.valueOf(x));
out.println(line);
}
}
}
}
2. Read every integer in a file, sum them, and write the result to another file. The file may contain other text, so skip tokens that aren’t numbers:
static long sumIntegersInFile(Path in, Path out) throws IOException {
long total = 0;
try (Scanner sc = new Scanner(in)) {
while (sc.hasNext()) {
if (sc.hasNextLong()) total += sc.nextLong();
else sc.next(); // skip non-numeric tokens
}
}
Files.writeString(out, total + System.lineSeparator());
return total;
}
3. Read students from a CSV file and write a report. Each line of students.txt looks like Name,Score. Read it with a BufferedReader, turn each line into a Student object, compute the average, then use a PrintWriter to write report.txt as an aligned table of name, score (2 decimals) and PASS/FAIL (pass at 5 or more), with the average at the bottom. Finally print Report generated successfully to report.txt.
Solution to exercise 3: full StudentReport, output and what a senior adds
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class StudentReport {
record Student(String name, double score) {
boolean passed() { return score >= 5.0; }
}
// Steps 1-2: read "Name,Score" lines, skip blank lines, report bad lines with their line number
static List<Student> readStudents(Path file) throws IOException {
List<Student> students = new ArrayList<>();
try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
String line;
int lineNo = 0;
while ((line = reader.readLine()) != null) {
lineNo++;
if (line.isBlank()) continue;
String[] parts = line.split(",");
try {
if (parts.length != 2) throw new IllegalArgumentException("expected exactly 2 columns");
String name = parts[0].strip();
double score = Double.parseDouble(parts[1].strip());
if (name.isEmpty() || score < 0 || score > 10) throw new IllegalArgumentException("empty name or score outside [0, 10]");
students.add(new Student(name, score));
} catch (IllegalArgumentException e) { // NumberFormatException is an IllegalArgumentException too
System.err.printf("Skipping line %d \"%s\": %s%n", lineNo, line, e.getMessage());
}
}
}
return students;
}
// Steps 3-4: compute the average and write an aligned report
static void writeReport(List<Student> students, Path file) throws IOException {
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(file, StandardCharsets.UTF_8))) {
out.println("====== STUDENT REPORT ======");
out.printf(Locale.ROOT, "%-12s%8s%10s%n", "Name", "Score", "Pass/Fail");
out.println("-".repeat(30));
double sum = 0;
for (Student s : students) {
out.printf(Locale.ROOT, "%-12s%8.2f%10s%n", s.name(), s.score(), s.passed() ? "PASS" : "FAIL");
sum += s.score();
}
out.println("-".repeat(30));
if (students.isEmpty()) out.println("Average Score: N/A");
else out.printf(Locale.ROOT, "Average Score: %.2f%n", sum / students.size());
out.println("=".repeat(30));
if (out.checkError()) throw new IOException("Failed to write " + file);
}
}
public static void main(String[] args) throws IOException {
List<Student> students = readStudents(Path.of("students.txt"));
writeReport(students, Path.of("report.txt"));
System.out.println("Report generated successfully to report.txt"); // step 5
}
}
Run against a file with five valid lines, a blank line, a Broken line and a Lan,abc line: the two bad lines are reported on System.err with their line numbers, and the rest still makes it into the report:
====== STUDENT REPORT ======
Name Score Pass/Fail
------------------------------
hoidanit 8.50 PASS
Nam 6.00 PASS
An 9.20 PASS
Eric 7.50 PASS
Mai 4.25 FAIL
------------------------------
Average Score: 7.09
==============================
%-12sleft-aligns in 12 columns and%8.2fright-aligns in 8 with 2 decimals, so the columns line up whatever the name length. The sample in the original task is aligned by hand, and its columns drift.- An empty file prints
N/Ainstead of dividing by zero. PrintWriterdoesn’t throw on failed writes, so callcheckError()before closing.- What a senior would add: use a CSV library (Apache Commons CSV, Jackson CSV), because real CSV has quoted commas, BOMs and header rows; decide explicitly what to do with bad lines (skip and log, or fail the whole batch); write the report to a temp file and
ATOMIC_MOVEit so nobody reads a half-written report.
Remember
- Can you explain why
nextLine()afternextInt()returns an empty string, and the two fixes? - Do you know which APIs overwrite by default, and how to append with both
FileWriterandFiles? - Can you explain the order try-with-resources closes things in, and how suppressed exceptions keep the original error?
- Do you know when to use
readAllLines,Files.linesorBufferedReader, and why to pass an explicit charset? - Can you write the temp-file-in-the-same-directory plus
ATOMIC_MOVEpattern, and say why not/tmp?
Interview questions
Junior
Why does nextLine() return an empty string right after nextInt()?
Because nextInt() reads only the number and leaves the line break in the buffer.
nextLine() immediately reads up to that line break and returns an empty string. Either add an extra nextLine() to consume it, or always read whole lines and parse them yourself.
Does FileWriter overwrite or append? How do you append?
It overwrites by default; to append use new FileWriter(path, true) or pass StandardOpenOption.APPEND.
FileWriter, PrintWriter and Files.write/writeString all create a new file or overwrite the existing one. With Files: Files.writeString(path, text, StandardOpenOption.CREATE, StandardOpenOption.APPEND). For real logging, use a logging library, which also handles appending, file rotation and concurrent writes from many threads.
Mid
Why use try-with-resources for files?
So close() always runs, even on an exception: buffers get flushed and file descriptors get released.
If both the body and close() throw, the close() exception is attached to the primary one as a suppressed exception, so the original error isn’t lost. Any AutoCloseable works with it.
Files.readAllLines, Files.lines or BufferedReader: which do you pick?
Small file: readAllLines/readString; large file: Files.lines; per-line control: BufferedReader.
readAllLines/readStringload the whole file into memory, are concise and close the file themselves: fine for small files (config, a few MB).Files.linesreturns a lazyStream<String>with constant memory however big the file is, but it must be closed with try-with-resources.BufferedReader.readLinein a loop is lazy too, and suits counting lines, per-line error handling or stopping early.- Specify the charset in all three.
Why should you specify a charset when reading or writing text? What changed in Java 18?
Because a file only holds bytes: decode them with the wrong charset and you get wrong text with no exception. Java 18 (JEP 400) made UTF-8 the default on every platform.
Vietnamese turning into Viá»t is the classic example. Before Java 18, FileReader, FileWriter, Scanner(File) and String.getBytes() used the OS default encoding, so the same code worked on macOS and broke on Windows. Still, write StandardCharsets.UTF_8 explicitly so the code is correct on older JDKs and the intent is obvious.
Senior
How would you process a 20 GB log file?
Stream it lazily line by line with Files.lines or a BufferedReader so memory stays constant; never readAllLines, which blows the heap.
Specify the charset. If speed matters, split the file into byte ranges and process them in parallel, use memory-mapped I/O (FileChannel.map), or move to a stream- or batch-processing tool. Measure before you optimize.
How do you write a file so other processes never read a half-written version?
Write to a temp file in the same directory, close it, then Files.move(tmp, target, ATOMIC_MOVE, REPLACE_EXISTING).
The rename is atomic at the OS level, so readers see either the old file or the complete new one. If you must be sure the data reached the disk before the rename (to survive a power cut), call FileChannel.force(true) on the temp file. A temp file in another directory (such as /tmp) may be on a different filesystem, and then the move is no longer atomic.
Useful phrases for interviews
- “I always wrap I/O in try-with-resources so the handle is released even on failure.”
- “For a file that doesn’t fit in memory, I stream it lazily instead of loading it all at once.”
- “I always pass an explicit charset when turning bytes into text.”
- “
FileWriteroverwrites by default; I passtrueorAPPENDwhen I need append mode.” - “We write to a temp file and do an atomic move, so readers never see a partial file.”
- “We log malformed lines with their line number and keep processing the rest of the batch.”
- “For anything beyond trivial CSV I’d use a proper parser, because quoted fields can contain the delimiter.”
- “
PrintWriterswallows I/O errors, so I checkcheckError()or use aBufferedWriterthat throws.”
Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words.