Input / Output

63
2 Unit 13 Input / Output 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

description

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 - PowerPoint PPT Presentation

Transcript of Input / Output

Page 1: Input / Output

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

Page 2: Input / Output

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

• ...

Page 3: Input / Output

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.

Page 4: Input / Output

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.

Page 5: Input / Output

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, …

Page 6: Input / Output

7Unit 13

ScenarioScenario

Application

Page 7: Input / Output

8Unit 13

PitStop: Basic PlumbingPitStop: Basic Plumbing!!

Water at home:

Water

Reservoir

Main Pipe Sec. Pipe Filter

Page 8: Input / Output

9Unit 13

Water At Home: ReadingWater At Home: Reading

Water

Reservoir

Main Pipe Sec. Pipe Filter

File (Source)

FileInputStream

DataInputStream

BufferedInputStream

Page 9: Input / Output

10Unit 13

Water From Home - DrainWater From Home - Drain

Sink (Drain)

Source Pipe FilterDest. Pipe

Destination

Page 10: Input / Output

11Unit 13

Water From Home: WritingWater From Home: Writing

Sink (Drain)

Source Pipe FilterDest. Pipe

Destination

ByteArray

byte[] arr;

ByteArrayOutputStream

BufferedOutputStream

FileOutputStream

File

Page 11: Input / Output

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.

Page 12: Input / Output

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.

Page 13: Input / Output

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

Page 14: Input / Output

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

Page 15: Input / Output

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.

Page 16: Input / Output

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.

Page 17: Input / Output

18Unit 13

InputStream

ByteArrayInputStream

FileInputStream BufferedInputStream

. . .

Specific input streamsSpecific input streams

Page 18: Input / Output

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.

Page 19: Input / Output

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.

Page 20: Input / Output

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.

Page 21: Input / Output

22Unit 13

Specific output streamsSpecific output streams

OutputStream

ByteArrayOutputStream

FileOutputStream BufferedOutputStream

Page 22: Input / Output

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

Page 23: Input / Output

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…

Page 24: Input / Output

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”); }}

Page 25: Input / Output

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…

Page 26: Input / Output

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”); }}

Page 27: Input / Output

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”); } }

Page 28: Input / Output

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(); }}

Page 29: Input / Output

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.

Page 30: Input / Output

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, ...

Page 31: Input / Output

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

Page 32: Input / Output

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.

Page 33: Input / Output

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

Page 34: Input / Output

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

Page 35: Input / Output

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

Page 36: Input / Output

37Unit 13

Specific readersSpecific readers

Reader

CharArrayReader

FileReader BufferedReader

. . .

StringReader

Page 37: Input / Output

38Unit 13

Specific WritersSpecific Writers

Writer

CharArrayWriter

FileWriter BufferedWriter

. . .

StringWriter

Page 38: Input / Output

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)

Page 39: Input / Output

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.

Page 40: Input / Output

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];

Page 41: Input / Output

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.”); }}

Page 42: Input / Output

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.

Page 43: Input / Output

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.

Page 44: Input / Output

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(); }}

Page 45: Input / Output

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.

Page 46: Input / Output

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.

Page 47: Input / Output

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.

Page 48: Input / Output

49Unit 13

Example: BufferedReaderExample: BufferedReader

Reader

read()

...

...

BufferedReader

readLine()

read()

...

...

Page 49: Input / Output

50Unit 13

Example: DataInputStreamExample: DataInputStream

InputStream

read()

...

...

DataInputStream

readShort()

read()

...

...

Page 50: Input / Output

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.

Page 51: Input / Output

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

Page 52: Input / Output

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());

}}

}

Page 53: Input / Output

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]));

Page 54: Input / Output

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

Page 55: Input / Output

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.

Page 56: Input / Output

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

Page 57: Input / Output

58Unit 13

ObjectInputStreamObjectInputStream

The class allows reading objects from an underlying InputStream. It contains the following method:

public Object readObject() throws IOException, ClassNotFoundException

Page 58: Input / Output

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!

Page 59: Input / Output

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…

Page 60: Input / Output

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…

Page 61: Input / Output

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.

Page 62: Input / Output

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){ }

}

Page 63: Input / Output

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){

} }