Essay
Learning Java, Part 10: Input and Output
Study notes on byte and character streams, the predefined streams, reading and writing files, try-with-resources, binary data, random-access files, buffered readers and writers, converting numeric strings with the type wrappers, and the modern java.nio.file API. Written entirely by an AI model.
Python opens a file with one function and reads it with a loop. Java’s I/O library is larger and older, built from small classes that you stack together. This part explains the design the book teaches, then shows the shorter modern API you will use most of the time.
Streams
In java.io, a stream is a sequence of data flowing in or out. There are two families:
| Input | Output | Unit | |
|---|---|---|---|
| Byte streams | InputStream |
OutputStream |
raw bytes: images, binary files |
| Character streams | Reader |
Writer |
text, with an encoding |
Each family has concrete classes for a source (FileInputStream, FileReader) and wrapper classes that add features to another stream (BufferedReader adds line reading, DataOutputStream adds writing ints and doubles). You build what you need by wrapping one inside another. This is called the decorator pattern, and you will meet it again in CITS4401.
The predefined streams
System.out and System.err are PrintStreams (for normal output and error messages); System.in is an InputStream connected to the keyboard. System.err usually appears on the screen as well, but it can be redirected separately.
try-with-resources
Every open file holds an operating system resource and must be closed, even when an exception is thrown halfway through. Before Java 7 that meant a finally block with its own nested try. Now you declare resources in parentheses after try, and Java closes them automatically, in reverse order, however the block ends:
import java.io.*;
public class WriteRead {
public static void main(String[] args) {
File f = new File("menu.txt");
try (PrintWriter out = new PrintWriter(new FileWriter(f))) {
out.println("green,3.50");
out.println("oolong,4.20");
out.printf("black,%.2f%n", 3.0);
} catch (IOException e) {
System.out.println("write failed: " + e.getMessage());
}
try (BufferedReader in = new BufferedReader(new FileReader(f))) {
String line;
while ((line = in.readLine()) != null) { // null means end of file
String[] parts = line.split(",");
double price = Double.parseDouble(parts[1]);
System.out.println(parts[0] + " costs " + price);
}
} catch (IOException e) {
System.out.println("read failed: " + e.getMessage());
}
f.delete();
}
}
green costs 3.5
oolong costs 4.2
black costs 3.0
- Any class that implements
AutoCloseablecan go in the parentheses. readLine()returns the next line without its newline, ornullat the end of the file. Thewhile ((line = ...) != null)idiom assigns and tests in one step.FileWriterreplaces an existing file;new FileWriter(f, true)appends.printfandString.formatuse format codes like Python’s old%formatting:%dinteger,%.2ftwo decimals,%sstring,%nnewline.- Opening a missing file for reading throws
FileNotFoundException, a subclass ofIOException. All of these are checked (Part 9), so the compiler insists you handle them.
Byte streams and binary data
Byte streams copy files exactly, which suits images and other binary formats. read() returns one byte as an int from 0 to 255, or −1 at the end:
import java.io.*;
public class CopyBytes {
public static void main(String[] args) throws IOException {
try (FileOutputStream out = new FileOutputStream("a.bin")) {
out.write(new byte[] {1, 2, 3, (byte) 200});
}
int count = 0, sum = 0, b;
try (FileInputStream in = new FileInputStream("a.bin")) {
while ((b = in.read()) != -1) {
count++;
sum += b;
}
}
System.out.println(count + " bytes, sum " + sum);
new File("a.bin").delete();
}
}
4 bytes, sum 206
Declaring main ... throws IOException is acceptable in short examples; an uncaught exception will just stop the program.
DataOutputStream and DataInputStream write and read primitive values in a fixed binary format. They must be read back in the order and types they were written:
import java.io.*;
public class DataDemo {
public static void main(String[] args) throws IOException {
try (DataOutputStream out = new DataOutputStream(new FileOutputStream("d.bin"))) {
out.writeInt(42);
out.writeDouble(3.5);
out.writeBoolean(true);
}
try (DataInputStream in = new DataInputStream(new FileInputStream("d.bin"))) {
System.out.println(in.readInt() + " " + in.readDouble() + " " + in.readBoolean());
}
System.out.println(new File("d.bin").length() + " bytes");
new File("d.bin").delete();
}
}
42 3.5 true
13 bytes
An int is 4 bytes, a double is 8 and a boolean is 1. That is 13.
Random-access files
RandomAccessFile can move to any position with seek(bytePosition) before reading or writing. With fixed-size records you can reach record n directly at byte n * recordSize. Most programs today use a database for this.
Character streams and the console
Character streams convert bytes to characters using an encoding. To read lines from the keyboard with them, wrap System.in:
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String line = console.readLine();
Scanner (Part 3) does the same with less code and also parses numbers.
FileReader and FileWriter use the platform’s default encoding, which is UTF-8 on modern JDKs (since Java 18). To be explicit, pass StandardCharsets.UTF_8.
Converting numeric strings
Text read from a file or keyboard is a String. The type wrapper classes (Part 12) parse it:
| Method | Example |
|---|---|
Integer.parseInt(s) |
"42" to 42 |
Long.parseLong(s) |
|
Double.parseDouble(s) |
"3.5" to 3.5 |
Boolean.parseBoolean(s) |
"TRUE" to true; anything else is false |
Integer.parseInt(s, 2) |
"1010" in base 2 to 10 |
Bad input throws NumberFormatException, which is unchecked. Strip surrounding spaces first with strip(), because Integer.parseInt(" 4") fails.
The modern way: java.nio.file
Since Java 7 (with additions in 11), java.nio.file.Files and Path do common jobs in one line. Use these for new code, and know the stream classes because the book, older code and exam questions use them.
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
public class NioDemo {
public static void main(String[] args) throws IOException {
Path p = Path.of("notes.txt");
Files.writeString(p, "one\ntwo\nthree\n");
List<String> lines = Files.readAllLines(p);
System.out.println(lines.size() + " lines, second is " + lines.get(1));
System.out.println(Files.exists(p) + " " + Files.size(p));
try (var stream = Files.lines(p)) { // lazy, for large files
System.out.println(stream.filter(s -> s.contains("t")).count());
}
Files.delete(p);
System.out.println(Files.exists(p));
}
}
3 lines, second is two
true 14
2
false
Files.lines returns a stream (Part 14) that reads lazily, so it must be closed; the try-with-resources does that.
Exam-style checks
- What is the difference between a byte stream and a character stream? When would you use each?
- Rewrite a file-reading method that uses
finallyto close the file as a try-with-resources. - What does
readLine()return at the end of a file? What doesread()return? - Why does reading a file need a
tryor athrowsclause, butInteger.parseIntdoes not?
Where to practise
Schildt’s Chapter 10 has a file comparison utility (report the first byte at which two files differ) and a disk-based version of the help system. Write both. Then write a program that reads a CSV of student marks, prints the average per student, and writes the results to a new file, handling a missing file and a badly formatted line separately.