unit 13 1 input / output streams h input/output h io streams, design aspects h specific io streams:...
Post on 21-Dec-2015
235 Views
Preview:
TRANSCRIPT
2Unit 13
Input / OutputInput / 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
3Unit 13
Input / OutputInput / 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
• ...
4Unit 13
GUI inputs and outputsGUI 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.
5Unit 13
IO API - design goalIO 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.
6Unit 13
Example: image processingExample: 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, …
7Unit 13
ScenarioScenario
Application
8Unit 13
PitStop: Basic PlumbingPitStop: Basic Plumbing!!
Water at home:
Water
Reservoir
Main Pipe Sec. Pipe Filter
9Unit 13
Water At Home: ReadingWater At Home: Reading
Water
Reservoir
Main Pipe Sec. Pipe Filter
File (Source)
FileInputStream
DataInputStream
BufferedInputStream
10Unit 13
Water From Home - DrainWater From Home - Drain
Sink (Drain)
Source Pipe FilterDest. Pipe
Destination
11Unit 13
Water From Home: WritingWater From Home: Writing
Sink (Drain)
Source Pipe FilterDest. Pipe
Destination
ByteArray
byte[] arr;
ByteArrayOutputStream
BufferedOutputStream
FileOutputStream
File
12Unit 13
I/O AbstractionI/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.
13Unit 13
Input/Output streamsInput/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.
14Unit 13
12 72 32 17 83 11 7 91 108
43 55 31 37 34 13 17 1 15
Input streamreading direction
writing direction
IO StreamsIO Streams
15Unit 13
Input streamsInput 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
16Unit 13
Class InputStreamClass 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.
17Unit 13
Class InputStream (Cont.)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.
18Unit 13
InputStream
ByteArrayInputStream
FileInputStream BufferedInputStream
. . .
Specific input streamsSpecific input streams
19Unit 13
Output streamsOutput 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.
20Unit 13
Class OutputStreamClass 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.
21Unit 13
Class OutputStream (Cont.)Class OutputStream (Cont.)
public void flush() throws IOExceptionFlushes 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.
22Unit 13
Specific output streamsSpecific output streams
OutputStream
ByteArrayOutputStream
FileOutputStream BufferedOutputStream
23Unit 13
Reading/Writing from/to filesReading/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
24Unit 13
Example (writing to a file)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…
25Unit 13
Example (writing to a file) (cont.)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”); }}
26Unit 13
Example (reading from a file)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…
27Unit 13
Example (reading from a file)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”); }}
28Unit 13
Example (downloading a file)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”); } }
29Unit 13
Downloading a file (cont.)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(); }}
30Unit 13
Textual vs. binary dataTextual 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.
31Unit 13
Text filesText files
Many operating systems use ASCII to store text ASCII include codes for 128 symbols including:
uppercase letterslowercase letterspunctuationdigitsspecial symbolscontrol characters
A B C …a b c …. , ; … 0 1 2 …& | \ …carriage return, tab, ...
32Unit 13
UnicodeUnicode
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
33Unit 13
Textual vs. binary dataTextual vs. binary data
Java makes a distinction between textual data and binary data
This distinction comes to gap between the non-standard 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.
34Unit 13
Readers & WritersReaders & 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
35Unit 13
Readers & WritersReaders & WritersWriter writer = new FileWriter(“mail.txt”);
writer.write(‘a’);
writer.write(‘\u0590’); // Aleph
Automatic platform
dependent translation
made by the writer
97
97
1424
224
97 224
standard ASCII no
conversion needed
36Unit 13
Readers & WritersReaders & Writers
Reader reader = new FileReader(“mail.txt”);
char c = reader.read(); // c = ‘\u0590’
c = reader.read(); // c = ‘a’
Automatic platform
dependent translation
made by the reader
97
97
1424
224
97 224
standard ASCII no
conversion needed
37Unit 13
Specific readersSpecific readers
Reader
CharArrayReader
FileReader BufferedReader
. . .
StringReader
38Unit 13
Specific WritersSpecific Writers
Writer
CharArrayWriter
FileWriter BufferedWriter
. . .
StringWriter
39Unit 13
Class java.io.ReaderClass 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)
40Unit 13
Class java.io.WriterClass 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.
41Unit 13
Example: Reader WriterExample: Reader Writerimport 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];
42Unit 13
Example (cont.)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.”); }}
43Unit 13
Streams (Summary – so far)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.
44Unit 13
Filters (the problem)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.
45Unit 13
Reading text lines (the hard way)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(); }}
46Unit 13
Design problemDesign 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.
47Unit 13
Solution - Decorator PatternSolution - 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.
48Unit 13
Solution - FiltersSolution - 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.
49Unit 13
Example: BufferedReaderExample: BufferedReader
Reader
read()
...
...
BufferedReader
readLine()
read()
...
...
50Unit 13
Example: DataInputStreamExample: DataInputStream
InputStream
read()
...
...
DataInputStream
readShort()
read()
...
...
51Unit 13
Source vs. Filter StreamsSource vs. Filter Streams
In the plumbing example we saw that there are 2 different kinds of Input/Output Streams:
1. Source Streams: Streams that are designed to connect to a specific source such as: FileInputStream, ByteArrayInputStream, etc.
2. Filter Streams: Streams that are designed to connect to other streams – that may offer some more functionality. For example: BufferedInputStream, DataInputStream, etc.
52Unit 13
Example: MyTypeExample: MyTypeimport 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
53Unit 13
MyType (cont.)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());
}}
}
54Unit 13
Java- Shorthand 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]));
55Unit 13
Example: Chaining StreamsExample: Chaining Streams
try { DataInputStream input = new DataInputStream( new BufferedInputStream( new FileInputStream(args[0])));} catch (FileNotFoundException fnfe) { // ...}
readShort()
read() read() read()
BufferedDataFile
56Unit 13
Object Input & Output StreamsObject 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 non-primitive (ref to an object).
This process is termed Serialization: serializing the object’s data members into a stream.
57Unit 13
ObjectOutputStreamObjectOutputStream
The class ObjectOutputStream allows writing an object into a stream. It contains the following method:
public void writeObject(Object obj)
throws IOException
58Unit 13
ObjectInputStreamObjectInputStream
The class allows reading objects from an underlying InputStream. It contains the following method:
public Object readObject() throws IOException, ClassNotFoundException
59Unit 13
SerializationSerialization
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!
60Unit 13
Serialization - ExampleSerialization - 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…
61Unit 13
Example (cont.)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…
62Unit 13
Example (cont.)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.
63Unit 13
Saving a WordCounter ObjectSaving a WordCounter Objectpublic 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){ }
}
64Unit 13
Loading a WordCounter ObjectLoading a WordCounter Objectpublic 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){
} }
top related