- Forward


Raw Input and Output in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Background
Back SMYC Forward
  • The Foundation:
    • Most text I/O in Java is stream oriented
  • An Important Design Pattern:
    • Raw I/O in Java makes heavy use of the decorator pattern (however, since there is no interface at the top, each decorator both extends its parent and delegates important operations to its parent)
Raw I/O Fundamentals
Back SMYC Forward
  • Purpose:
    • Provide the ability to read and write bytes
  • History:
    • Was originally the only way to do I/O in Java until support for character encodings was added
Important Examples
Back SMYC Forward
  • Standard Error/Output:
    • System.out is a PrintStream object
    • System.err is a PrintStream object
  • Standard Input:
    • System.in is a InputStream object
Some Streams for Input
Back SMYC Forward
streams_input
Some Streams for Output
Back SMYC Forward
streams_output
The OutputStream Class
Back SMYC Forward
  • The write() Methods:
    • Write a byte or array of bytes
  • Other Methods:
    • close()
    • flush()
  • Assessment:
    • Is not "friendly" but can be decorated to add functionality
The PrintStream Class
Back SMYC Forward
  • The print() and println() Methods:
    • Versions for all standard types (overloaded)
    • Unformatted
    • Print a single value
  • The printf() Method:
    • A convenient way to use format strings (which are encapsulated in Formatter ) to format and print multiple values at the same time
The InputStream Class
Back SMYC Forward
  • The read Methods:
    • Read a byte or array of bytes
    • Is not "friendly"
  • Other Methods:
    • available()
    • skip()
  • Assessment:
    • Is not "friendly" but can be decorated to add functionality
The DataInputStream Class
Back SMYC Forward
  • The readLine() Method:
    • Reads a complete line, returning a String
    • Has been deprecated because of conversion problems
  • Other Methods:
    • Can be used to read primitive data types
Reading Until End-of-Stream
Back SMYC Forward
javaexamples/streams/Googler.java
 
Motivating Piped Streams
Back SMYC Forward

A Driver for the Googler

javaexamples/streams/GooglerDriver1.java
 
Motivating Piped Streams (cont.)
Back SMYC Forward
  • A Problem with the Driver:
    • You can't prompt the user for each line of input
  • A Solution:
    • Use piped streams
  • A Warning:
    • The source and sink should be accessed from different threads
A Factory for Piped Streams
Back SMYC Forward
javaexamples/streams/PipedStreamFactory.java
 
Using Piped Streams
Back SMYC Forward

A Better Driver for the Googler

javaexamples/streams/GooglerDriver2.java
 
Using a Byte Array Stream
Back SMYC Forward
Putting a String in a Stream
javaexamples/streams/StreamFactory.java (Fragment: String)
 
There's Always More to Learn
Back -