Transcript Unit 13

Input / Output


A program often needs to communicate with other
devices. In other words it should receive input and
send output.
There are many types of input sources:
• Reading a file from a local disk / diskette
• Receiving a web page from a remote server
• Receiving a communication message through a
network. Receiving a signal from a sensor of a
robot
• Scanner, video camera, ...
• Mouse, keyboard, joystick
2
Unit 13
Input / Output

Similarly, there are many types of output
destinations:
• Writing to a file on a local disk / diskette
• Sending query information to a remote web server
• Sending communication message to a remote host.
Sending a command to a robot controller.
• Printing a document to a printer / fax
• Displaying graphics on the screen
• ...
3
Unit 13
GUI inputs and outputs


GUI related inputs and outputs are usually treated
separately. They are given special API about
which we will not talk about here.
GUI inputs and outputs include receiving mouse,
keyboard and similar events, and displaying
graphics on the screen.
4
Unit 13
IO API - design goal



We want to make a distinction between the content
of the data an application receives/sends and the
source/destination of the data
The same kind of data can be stored on different
types of media.
Similarly a given media can store different types
of data.
5
Unit 13
Example: image processing



Suppose we have an image processing application.
It can read images, manipulate them and store
them on a permanent storage.
We want our application to be able to read images
from different types of sources:local image files,
remote images from the web, receiving an image
from a scanner, ...
We want to be able to output the image to various
types of destinations:save the image to a local file,
print the image on a printer, send the image to a
fax recipient, …
6
Unit 13
Scenario
Application
7
Unit 13
PitStop: Basic Plumbing!

Water at home:
Water
Main Pipe
Sec. Pipe
Filter
Reservoir
8
Unit 13
Water At Home: Reading
DataInputStream
Water
Main Pipe
Sec. Pipe
Filter
Reservoir
FileInputStream
BufferedInputStream
File
(Source)
9
Unit 13
Water From Home - Drain
Destination
Dest. Pipe
Filter
Source Pipe
Sink
(Drain)
10
Unit 13
Water From Home: Writing
File
ByteArrayOutputStream
Destination
Filter
Dest. Pipe
Source Pipe
Sink
(Drain)
BufferedOutputStream
ByteArray
FileOutputStream
byte[] arr;
11
Unit 13
I/O Abstraction



We can achieve the separation by designing a
common interface for reading any kind of data,
and common interface for writing any kind of
data.
This interface is implemented by the notion of
input and output streams.
Any input/output can be represented as a sequence
of bits. For convenience we divide the sequence
into a sequence of bytes.
12
Unit 13
Input/Output streams


An input/output stream is a sequence of bytes that
is attached to some input/output source.
You can read/write data from/to the stream in a
sequential order. One byte at a time or several
bytes at a time.
13
Unit 13
IO Streams
12
72
32
17
83
11
7
91
108
Input stream
reading direction
43
55
31
37
34
13
17
1
15
writing direction
14
Unit 13
Input streams





An input stream is a sequence of bytes that is attached to
some input source.
You can read data from the stream in a sequential order.
One byte at a time or several bytes at a time.
Input streams are represented by the abstract class
java.io.InputStream.
Subclasses of InputStream defines input streams that are
related to various data sources
Class InputStream gives a common interface for receiving
data from various types of data sources
15
Unit 13
Class InputStream

Class java.io.InputStream defines several methods that
support the abstraction of allowing sequential reading
from a stream:
public abstract int read()
throws IOException
Reads the next byte from the stream. Return -1 if the end of
the stream was reached.
public int read(byte[] b)
throws IOException
Reads up to b.length bytes from the stream into the array b.
Returns the number of bytes that were read.
16
Unit 13
Class InputStream (Cont.)
public void close() throws IOException
Closes this input stream and releases any system
resources associated with the stream.
Opening A file is done using the constructor.
17
Unit 13
Specific input streams
InputStream
...
FileInputStream
BufferedInputStream
ByteArrayInputStream
18
Unit 13
Output streams





An output stream is attached to an output destination to
which you can write data.
You can write data to the stream in a sequential order. One
byte at a time or several bytes at a time.
Output streams are represented by the abstract class
java.io.OutputStream.
Subclasses of OutputStream defines output streams that are
related to various data destinations
Class OutputStream gives a common interface for sending
data to various types of data destinations.
19
Unit 13
Class OutputStream

Class java.io.OutputStream defines several methods that
support the abstraction of allowing sequential writing to a
stream:
public abstract void write(int b)
throws IOException
Writes the specified byte (given as an int) to this output
stream.
public void write(byte[] b)
throws IOException
Writes b.length bytes from the specified byte array to this
output stream.
20
Unit 13
Class OutputStream (Cont.)
public void flush() throws IOException
Flushes this output stream and forces any buffered output
bytes to be written out.
public void close() throws IOException
Closes this output stream and releases any system
resources associated with the stream.
21
Unit 13
Specific output streams
OutputStream
FileOutputStream
BufferedOutputStream
ByteArrayOutputStream
22
Unit 13
Reading/Writing from/to files



java.io.FileInputStream is a subclass of
InputStream that let you read a file (viewed as a
sequence of bytes)
java.io.FileOutputStream is a subclass of
OutputStream that let you write data to a file (as a
sequence of bytes)
Both classes have constructors that get the path of
the file as a parameter
23
Unit 13
Example (writing to a file)
import java.io.*;
// Creates a file that stores results of random
// tosses of a playing dice.
class GenerateDiceData {
static final String FILENAME = “dice.dat”;
static final int NUMBER_OF_TOSSES = 100000;
public static void main(String[] args) {
//continued on next slide…
24
Unit 13
Example (writing to a file) (cont.)
try {
OutputStream output =
new FileOutputStream(FILENAME);
for (long i=0; i<NUMBER_OF_TOSSES; i++) {
int result (int)(Math.random()*6)+1;
output.write(result);
}
output.flush();
output.close();
} catch (IOException ioe) {
System.err.println(
“Couldn’t write to file”);
}
}
25
Unit 13
Example (reading from a file)
// Reads from a file that represents results of
// a random tosses of a playing dice, and counts
// the number of times that the result 6 appears.
class CountOccurrences {
static final String FILENAME = “dice.dat”;
static final int LOOK_FOR = 6;
public static void main(String[] args) {
long count = 0;
//continued on next slide…
26
Unit 13
Example (reading from a file)
try {
InputStream input =
new FileInputStream(FILENAME);
int result;
while ((result = input.read()) != -1) {
if (result == LOOK_FOR) {
count++;
}
}
input.close();
System.out.println(count + “occurrences”);
} catch (IOException ioe) {
System.err.println(“Couldn’t read from
file”);
}
}
27
Unit 13
Example (downloading a file)
import java.io.*;
import java.net.URL;
// This program downloads a file from a given url
// and saves it to the local file
// Usage: java Download <url> <filename>
class Download {
public static void main(String[] args) {
try {
download(args[0], args[1]);
} catch (ArrayIndexOutOfBoundsException aioobe) {
System.err.println(“Wrong usage.”);
} catch (IOException ioe) {
System.err.println(“Download failed”);
}
28
}
Unit 13
Downloading a file (cont.)
// Downloads a remote file to the local disk.
// source - The url of the remote file
// filename - The name of the target file.
private static void download(String source,
String filename) throws IOExcption {
URL url = new URL(source);
InputSteram input = url.openStream();
OutputStream output =
new FileOutputStream(filename);
int b;
while ((b=input.read())!=-1) {
output.write(b);
}
output.close();
}
}
29
Unit 13
Textual vs. binary data




We often make a distinction between textual data
and other kind of data
We refer to files that stores text as ‘text files’ and
to other files as ‘binary files’.
Binary files stores their information in various
formats. In order to understand the content of a
binary file you need to have a viewer that knows
how to read the format the file is written with.
The structure of text files is more simple. It uses
an encoding that gives a numeric code for each
symbol and the text is stored as a list of numbers.
30
Unit 13
Text files


Many operating systems use ASCII to store text
ASCII include codes for 128 symbols including:
uppercase letters
lowercase letters
punctuation
digits
special symbols
control characters
A B C …
a b c …
.,; …
0 1 2…
& | \ …
carriage return, tab, ...
31
Unit 13
Unicode


Unicode defines a character set that includes most of
the languages in the world.
Unicode uses 16 bit for each characters, so it defines
65,536 characters. It has characters for:
• Greek, Hebrew, Arabic, Devangari, Bengali,
Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada,
Malyalam, Thai, Lao, Georgian, Hanguljamo, Latin,
Hiragana, Katakana, Bopomofo, Hangul, Jamo and
some more.
• More info http://www.unicode.org

The first 128 characters coincide with ASCII
32
Unit 13
Textual vs. binary data



Java makes a distinction between textual data and
binary data
This distinction comes to gap between the nonstandard representation of text by the operating
system and the standard unicode representation of
text in Java
Java defines a parallel set of classes for
reading/writing textual data.
33
Unit 13
Readers & Writers





java.io.Reader is an abstract class that defines a
common interface for reading textual data
It is the counterpart of InputStream
You can read from a reader characters in a sequential
manner. One character at a time, or several
characters at a time.
Similarly, java.io.Writer is an abstract class that
defines a common interface for writing textual data.
It is the counterpart of OutputStream
34
Unit 13
Readers & Writers
Writer writer = new FileWriter(“mail.txt”);
writer.write(‘a’);
writer.write(‘\u0590’); // Aleph
97
1424
Automatic platform
dependent translation
made by the writer
standard ASCII no
conversion needed
97
97
224
224
35
Unit 13
Readers & Writers
Reader reader = new FileReader(“mail.txt”);
char c = reader.read(); // c = ‘\u0590’
c = reader.read();
// c = ‘a’
97
1424
Automatic platform
dependent translation
made by the reader
standard ASCII no
conversion needed
97
97
224
224
36
Unit 13
Specific readers
Reader
...
FileReader
CharArrayReader
BufferedReader
StringReader
37
Unit 13
Specific Writers
Writer
...
FileWriter
CharArrayWriter
BufferedWriter
StringWriter
38
Unit 13
Class java.io.Reader
public abstract int read(char[] buffer,
int offset, int length) throws IOException
Reads up to ‘length’ characters into ‘buffer’ starting from
‘offset’, returns the number of characters read.
public void close() throws IOException
Closes the reader.

Few additional methods (look up in the API)
39
Unit 13
Class java.io.Writer
public void write(int c) throws IOException
Writes a single character given as an int.
public void write (char[] buffer)
throws IOException
Writes a given char array.
40
Unit 13
Example: Reader Writer
import java.io.*;
// This class reads a text file and writes it into
// another text file after converting all letters to
// uppercase.
// Usage: java ToUpper <source> <target>
class ToUpper {
public static void main(String[] args) {
if (args.length!=2) {
System.err.println(“Invalid usage.”);
return;
}
String sourceName = args[0];
String targetName = args[1];
41
Unit 13
Example (cont.)
try {
Reader reader = new FileReader(sourceName);
Writer writer = new FileWriter(targetName);
int c;
while ((c=reader.read())!=-1) {
c = Character.toUpperCase((char)c);
writer.write(c);
}
} catch (IOException ioe) {
System.err.println(“Copying failed.”);
}
}
42
Unit 13
Streams (Summary – so far)

InputStream and OutputStream gives us a low level
for reading and writing binary data. We can only
read/write a single byte or an array of bytes.

Likewise, Reader and Writer gives us a low level for
reading and writing text files. We can only
read/write a single char or an array of chars.
43
Unit 13
Filters (the problem)

The data we want to read/write however, usually
has a more complex structure:
• Textual data ordered in a table
• A list of short values every 2 bytes represent a
single short value

We would like to be able to read/write the data in a
structured way.
44
Unit 13
Reading text lines (the hard way)
Vector lines = new Vector();
Reader reader = new FileReader(FILE_NAME);
StringBuffer line = new StringBuffer();
int c;
while ((c = reader.read())!=-1) {
if (c!=‘\n’) {
line.append((char)c);
}
else {
lines.addElement(line.toString());
line = new StringBuffer();
}
}
45
Unit 13
Design problem


We would like to have methods for
reading/writing data on a higher level.
Problem:
• There are many enhancements for reading/writing
data
• There are many types of input/output streams
• If we would include all enhancements in all types
of streams we will end up with a lot of duplicated
code and it would be hard to add new
enhancements or new types of streams.
46
Unit 13
Solution - Decorator Pattern






Use a “decorator”: a class that is derived from Reader, and
has another Reader object as member (received by
constructor of new class).
All Reader methods are “forwaded” to the inner Reader
object.
New attributes (methods) use the inner Reader object as well.
We gain two things: The “old” interface is preserved, and we
can “chain” several functionalities.
Same solution for Writer, InputStream and OutputStream.
In Java, “decorators” are called “Filters”, and the base class
for adding attributes is FilterXXX.
47
Unit 13
Solution - Filters




Java solves this problem by use of filters.
For each enhancement for reading from an input
stream there is a suitable filter input stream.
For each enhancement for writing to an output
stream there is a suitable filter output stream
Similarly there are filter readers and filter writers.
48
Unit 13
Example: BufferedReader
BufferedReader
readLine()
Reader
read()
...
read()
...
...
...
49
Unit 13
Example: DataInputStream
DataInputStream
readShort()
InputStream
read()
...
read()
...
...
...
50
Unit 13
Source vs. Filter Streams

1.
2.
In the plumbing example we saw that there are 2
different kinds of Input/Output Streams:
Source Streams: Streams that are designed to
connect to a specific source such as:
FileInputStream, ByteArrayInputStream, etc.
Filter Streams: Streams that are designed to
connect to other streams – that may offer some
more functionality. For example:
BufferedInputStream, DataInputStream, etc.
51
Unit 13
Example: MyType
import java.io.*;
public class MyType {
public static void main(String[] args) {
if(args.length!=1){
System.out.println("usage: java”
+SuperMyType <file_name>");
System.exit(0);
}
//continued on next slide
52
Unit 13
MyType (cont.)
try {
FileInputStream in= new FileInputStream(args[0]);
BufferedInputStream buf=
new BufferedInputStream(in);
int c= buf.read();
while(c!=-1) {
System.out.print((char)c);
c= buf.read();
}
buf.close();
}catch(IOException ioe){
System.err.println("\nError: "+ioe.getMessage());
}
}
}
53
Unit 13
Java- Shorthand
Instead Of Writing:
FileInputStream in= new
FileInputStream(args[0]);
BufferedInputStream buf=
new BufferedInputStream(in);
We usually write:
BufferedInputStream buf=
new BufferedInputStream(
new FileInputStream(args[0]));
54
Unit 13
Example: Chaining Streams
try {
DataInputStream input = new DataInputStream(
new BufferedInputStream(
new FileInputStream(args[0])));
} catch (FileNotFoundException fnfe) {
// ...
}
read()
Data
read()
Buffered
read()
File
readShort()
55
Unit 13
Object Input & Output Streams




Java allows us to read and write whole objects into
a binary file.
The process of saving an objects state requires
saving all non-static data members it holds.
These data members may be primitive or nonprimitive (ref to an object).
This process is termed Serialization: serializing
the object’s data members into a stream.
56
Unit 13
ObjectOutputStream

The class ObjectOutputStream allows writing an
object into a stream. It contains the following
method:
public void writeObject(Object obj)
throws IOException
57
Unit 13
ObjectInputStream

The class allows reading objects from an
underlying InputStream. It contains the following
method:
public Object readObject() throws
IOException, ClassNotFoundException
58
Unit 13
Serialization



In order for an object to be written into an Object
Stream it must implement the interface
Serializable.
The interface is part of the java.io package.
The interface is an empty interface – i.e. no
methods are included in it!
59
Unit 13
Serialization - Example
import java.io.*;
public class WordEntry implements Serializable{
private String word;
private int counter;
public WordEntry(String word){
this.word= word;
counter=0;
}
//continued on next slide…
60
Unit 13
Example (cont.)
public void setCounter(int counter){
if(counter >0 )
this.counter= counter;
}
public int getCounter(){
return(counter);
}
public String getWord(){
return(word);
}
//continued on next slide…
61
Unit 13
Example (cont.)
public String toString(){
return("word= " + word + " counter= " + counter);
}
public boolean equals(Object obj){
if(!(obj instanceof WordEntry))
return(false);
WordEntry other= (WordEntry)obj;
return(this.word.equalsIgnoreCase(other.word));
}
}//end of class.
62
Unit 13
Saving a WordCounter Object
public static void main(String[] args){
WordCounter wCount= new WordCounter(“yes”,10”);
try{
ObjectOutputStream objOut=
new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(args[0])));
objOut.writeObject(wCount);
objOut.flush();
objOut.close();
}catch(IOException ioe){ }
}
63
Unit 13
Loading a WordCounter Object
public static void main(String[] args){
WordCounter wCount;
try{
ObjectInputStream objIn=
new ObjectInputStream(
new FileInputStream(args[0]));
wCount= (WordCounter)objIn.readObject();
objIn.close();
}catch(IOException ioe){
//do something
}catch(ClassNotFoundException cnfe){
}
}
64
Unit 13