Java Files buffered text I/O
Read and write text incrementally using buffered character streams.
A simple example
Files buffered text I/O
- Start with A line containing A, then end of file
- Do this Read one line
- Result A
Syntax
public static BufferedReader newBufferedReader(Path path, Charset cs) throws IOException
JDK 21 declarations (4)
public static BufferedReader newBufferedReader(Path path) throws IOExceptionpublic static BufferedReader newBufferedReader(Path path, Charset cs) throws IOExceptionpublic static BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOption... options) throws IOExceptionpublic static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPrint the next clinic appointment
A clinic export contains appointments in time order. The receptionist needs only the first name at opening time, so write two sample appointments and read one line without loading the whole schedule.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path schedule = desk.resolve("clinic.txt");
try (var writer = Files.newBufferedWriter(schedule)) {
writer.write("Ada"); writer.newLine(); writer.write("Lin");
}
try (var reader = Files.newBufferedReader(schedule)) {
System.out.println(reader.readLine());
}
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
Ada
The line reader consumes the first record. The second remains available to a later read on the same reader.
Distinguish a missing signature from the end of the file
A delivery list reserves a blank line for an unsigned handover. The importer must keep that blank record while recognizing that a later read can genuinely reach the end of input.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path sheet = Files.writeString(desk.resolve("handover.txt"), "\nAda");
try (var reader = Files.newBufferedReader(sheet)) {
System.out.println(reader.readLine().isEmpty());
System.out.println(reader.readLine());
System.out.println(reader.readLine() == null);
}
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true Ada true
A blank line produces an empty string. Only the read after Ada returns null.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Save the note and read it back before the desk closes. Which characters are recovered?
What to watch for
Close the writer before reopening the file for reading so buffered characters reach the underlying stream.