- Forward


Custom Streams
in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Java has an extensive "stream library"
  • There are still times when you need to write classes for handling custom streams
One Approach
Back SMYC Forward
  • Extend InputStream
  • Extend OutputStream
An Example
Back SMYC Forward
  • Motivation:
    • Many data types require more than one byte
    • Every system that uses such data types has to decide how these bytes will be ordered
    • In a little-endian scheme the least significant byte is first; in a big-endian scheme (a.k.a., network byte order) the most significant byte is first
  • One Approach:
    • First "stretch" each byte (e.g., into four bytes for an int) by performing a bitwise AND (e.g., i = b & 0x000000FF)
    • Then shift the bits(e.g., i = i << 8)
    • Then combine the bytes using a bitwise OR
An Example (cont.)
Back SMYC Forward
javaexamples/io/LittleEndianInputStream.java
 
An Example (cont.)
Back SMYC Forward
javaexamples/io/LittleEndianOutputStream.java
 
Another Example
Back SMYC Forward
  • Motivation for a Custom Input Stream:
    • To process HTTP requests you need to be able to read in both lines (i.e., sequences of characters terminated by CR LF) and arrays of bytes
    • The DataInputStream class does this but the readLine() method is deprecated
  • Motivation for a Custom Output Stream
    • Lines are terminated by a CR LF
Another Example (cont.)
Back SMYC Forward

Extending a DataInputStream

javaexamples/http/v0/HttpInputStream.java
 
Another Example (cont.)
Back SMYC Forward

Extending a PrintStream

javaexamples/http/v0/HttpOutputStream.java
 
There's Always More to Learn
Back -