Java I/O

lecture
java
file-io
streams
readers
writers
nio

See csse2002 for course logistics.

Topics

  1. Streams (java.io, since Java 1.0) — byte-oriented
  2. Readers & Writers (java.io, since Java 1.1) — character-oriented
  3. Scanner (java.util, since Java 1.5) — a convenience wrapper, neither stream nor reader
  4. 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 OutputStream and 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. InputStreamReader is the bridge back to the byte world.
  • Everything in java.io is 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 Path and Files.
  • 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

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.