O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

File Viewer, Part 2

There’s a saying among object-oriented programmers that you should create one design just to throw away. Now that we’ve got filter streams in hand, I’m ready to throw out the monolithic design for the FileDumper program used in Chapter 4. I’m going to rewrite it using a more flexible, extensible, object-oriented approach that relies on multiple chained filters. This allows us to extend the system to handle new formats without rewriting all the old classes. (It also makes some of the examples in subsequent chapters smaller, since I won’t have to repeat all the code each time.) The basic idea is to make each interpretation of the data a filter input stream. Bytes from the underlying stream move into the filter; the filter converts the bytes into strings. Since more bytes generally come out of the filter than go into it (for instance, the single byte 32 is replaced by the four bytes “0”, “3”, “2”, " " in decimal dump format), our filter streams buffer the data as necessary.

The architecture revolves around the abstract DumpFilter class shown in Example 6.9. The public interface of this class is identical to that of FilterInputStream . Internally, a buffer holds the string interpretation of each byte as an array of bytes. The read() method returns bytes from this array as long as possible. An index field tracks the next available byte. When index reaches the length of the array, the abstract fill() method is invoked to read from the underlying stream and place data ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required