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 anint0-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:
BufferedReaderforreadLine(),BufferedWriterfornewLine(),PrintWriterfor formatted output. ObjectOutputStream/ObjectInputStreamserialize objects whose classes implementSerializable.transientfields are skipped;staticfields are not serialized.- During deserialization, the constructor of a
Serializableclass does not run; the no-arg constructor of the first non-serializable superclass does. serialVersionUIDcontrols compatibility; a mismatch throwsInvalidClassException.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
Filerepresents a path, not open content;exists()andisDirectory()are metadata checks.- Forgetting to close a stream can lose buffered writes.
readLine()strips line terminators.- Serializing a non-serializable field throws
NotSerializableExceptionunless it istransient. - Using the platform default charset makes text I/O non-portable; specify a charset when it matters.