Java SE 8 Programmer II study materials
Java SE 8 Programmer II study resources

Java SE 8 Programmer II: Using the Java I/O API

Java SE 8 Programmer II · Work through your exam, one topic at a time.

All guide sections

Using the Java I/O API

Using the Java I/O API tests byte and character streams, buffering, serialization, and correct resource handling in java.io.

Core rules

  • Byte streams (InputStream/OutputStream) handle binary data; character streams (Reader/Writer) handle text and charset conversion.
  • FileInputStream.read() returns an int 0-255 or -1 at end; Reader.read() returns a character value or -1. Always test for -1 rather than casting blindly.
  • Wrap streams for performance and convenience: BufferedReader for readLine(), BufferedWriter for newLine(), PrintWriter for formatted output.
  • ObjectOutputStream/ObjectInputStream serialize objects whose classes implement Serializable. transient fields are skipped; static fields are not serialized.
  • During deserialization, the constructor of a Serializable class does not run; the no-arg constructor of the first non-serializable superclass does.
  • serialVersionUID controls compatibility; a mismatch throws InvalidClassException.
  • flush() pushes buffered data; close() flushes and releases the resource.

Worked example

try (BufferedReader br = new BufferedReader(new FileReader("in.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } readLine() returns null at end of stream, not -1. The try-with-resources closes the BufferedReader, which closes the underlying FileReader.

Traps

  • File represents a path, not open content; exists() and isDirectory() are metadata checks.
  • Forgetting to close a stream can lose buffered writes.
  • readLine() strips line terminators.
  • Serializing a non-serializable field throws NotSerializableException unless it is transient.
  • Using the platform default charset makes text I/O non-portable; specify a charset when it matters.