Lesson 14Working with I/O Streams

Most programs work with some kind of data, which could be stored in a local database, on a remote computer, or in a file located on your disk. Java has a concept of working with streams of data. You can say that a Java program reads sequences of bytes from an input stream (or writes into an output stream) byte after byte, character after character, primitive after primitive. Accordingly, Java defines various types of classes supporting streams; for example, InputStream or OutputStream. There are classes specifically meant for reading character streams such as Reader and Writer.  DataInputStream and DataOutputStream can read and write Java primitives, and to work with files you may consider such classes as FileInputStream and FileReader.

Classes that work with streams are located in two packages: java.io and java.nio. Classes from the former implement blocking input/output (I/O): When bytes are being read/written by a process, they become unavailable for other threads of execution. The latter package offers non-blocking I/O with improved performance. Most of this chapter covers the fundamentals of I/O, but at the end I’ll show you how to work with files using classes from the package java.nio.

Before deciding which Java class to use for I/O in each particular case, you need to understand what kind of data is coming from (or going to) the stream in question. No matter what you select, your code needs to perform three operations:

  1. Open a stream ...

Get Java Programming 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.