Java I/O
lecture
java
file-io
streams
readers
writers
nio
See csse2002 for course logistics.
Topics
- Streams (
java.io, since Java 1.0) — byte-oriented - Readers & Writers (
java.io, since Java 1.1) — character-oriented - Scanner (
java.util, since Java 1.5) — a convenience wrapper, neither stream nor reader - New I/O (
java.nio.file, since Java 1.7) — the file system itself
Instance Saving & Loading — saving and loading an object model to a file — is taken up in the Week 10 practical, week10-lab-java-io.
All content is in java-io.
The thread running through it
Each generation of the API is a response to what the previous one was awkward at:
- Byte streams give one uniform abstraction over any source or destination, so a method can take an
OutputStreamand not care whether it is a console, a file, or an array (see java-solid-principles — Liskov Substitution). - They were never ideal for text, so Readers & Writers were added to work in
chars and Unicode.InputStreamReaderis the bridge back to the byte world. - Everything in
java.iois assembled by wrapping one object around another — buffering, line-reading and formatting are separate classes you stack, not options on one class. - None of it was designed for managing files and directories, so New I/O adds
PathandFiles. - Every stream and reader must be closed;
try-with-resources is the way to do it (Effective Java Item 9). This is where the topic leans hardest on java-exceptions.
Summary — which to use? Streams for binary data, Readers & Writers for text, New I/O when manipulating a file system or file contents.
Set as homework
- Read through
flush(). - Scanner vs. BufferedReader on Stack Overflow.
- Rewrite the stream and reader exercises using New I/O.
Applied class
See week8-tutorial-class-invariants — protecting class invariants (a continuation of java-specification and java-encapsulation from earlier weeks).
Practical
See week8-lab-junit-testing — Test Driven Development with JUnit, extending java-junit from Week 5.