Appearance
Lesson 01 · I/O Streams & Readers
Objectives
After this lesson you will be able to:
- Tell byte streams from character streams and pick the right one.
- Wrap streams for buffering and use try-with-resources.
- Read user input from the console.
Don't confuse these "streams"
The I/O InputStream/OutputStream here are unrelated to the java.util.stream.Stream of Module 06. Same word, different worlds.
Byte vs character streams
| Byte streams | Character streams | |
|---|---|---|
| Base types | InputStream / OutputStream | Reader / Writer |
| Unit | raw bytes | char (text, with an encoding) |
| Use for | images, binary, any bytes | text |
java
// bytes
try (InputStream in = new FileInputStream("a.bin")) { int b = in.read(); }
// text
try (Reader r = new FileReader("a.txt")) { int c = r.read(); }A bridge converts bytes↔chars with an explicit charset: InputStreamReader / OutputStreamWriter.
Buffering
Wrap a raw stream in a buffered decorator to read/write in chunks — far fewer system calls. BufferedReader adds the handy readLine().
java
try (BufferedReader br = new BufferedReader(new FileReader("a.txt"))) {
String line;
while ((line = br.readLine()) != null) { process(line); }
}Exam trap
read() returns an int (the byte/char value, or -1 at end of stream), not a byte/char — this lets -1 signal EOF unambiguously. Storing it in a char/byte and comparing to -1loops forever. The decorator pattern wraps streams: new BufferedReader(new FileReader(...)).
Console input
java
// Modern, simple line input:
var br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();
// Console (null when not attached to a terminal, e.g. in an IDE/test):
Console c = System.console();
char[] pw = c.readPassword("Password: "); // doesn't echoSDET note
Don't hard-code System.in/System.out deep in logic — inject a Reader/Writer (or Appendable) so a test can supply a StringReader and capture a StringWriter. That makes I/O code unit-testable without touching the real console or filesystem.
Key Takeaways
- Byte streams (
InputStream/OutputStream) carry raw bytes; character streams (Reader/Writer) carry text with an encoding. Bridge withInputStreamReader/OutputStreamWriter. - Wrap in buffered decorators for efficiency;
BufferedReader.readLine()reads a line. read()returns anintand-1at EOF — never store it inchar/bytefor the EOF test.- Always use try-with-resources so streams close.
Lesson Quiz
What does InputStream.read() return at end of stream?
Which is a CHARACTER stream?
Why store read()'s result in an int, not a char?
What does BufferedReader add over a plain Reader?
Which bridges bytes to characters with a charset?
Next: NIO.2 Path & Files. Run the matching code in labs/src/main/java/com/jse21/m08_io/.