1 / 63

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

shanta
Télécharger la présentation

Input / Output

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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. 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. 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. 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. 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. Scenario Application

  7. PitStop: Basic Plumbing! • Water at home: Water Reservoir Main Pipe Sec. Pipe Filter

  8. Water At Home: Reading DataInputStream Water Reservoir Main Pipe Sec. Pipe Filter FileInputStream BufferedInputStream File (Source)

  9. Water From Home - Drain Destination Sink (Drain) Source Pipe Filter Dest. Pipe

  10. Water From Home: Writing File ByteArrayOutputStream Destination Sink (Drain) Source Pipe Filter Dest. Pipe BufferedOutputStream ByteArray byte[] arr; FileOutputStream

  11. 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 intoa sequence of bytes.

  12. 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. 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. 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. 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. 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. Specific input streams InputStream . . . FileInputStream BufferedInputStream ByteArrayInputStream

  18. 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. 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. 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. Specific output streams OutputStream FileOutputStream BufferedOutputStream ByteArrayOutputStream

  22. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Textual 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.

  33. 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. 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 97 224 standard ASCII no conversion needed 97 224

  35. 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 97 224 standard ASCII no conversion needed 97 224

  36. Specific readers Reader . . . FileReader BufferedReader CharArrayReader StringReader

  37. Specific Writers Writer . . . FileWriter BufferedWriter CharArrayWriter StringWriter

  38. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. BufferedReader readLine() read() ... ... Reader read() ... ... Example: BufferedReader

  49. Example: DataInputStream DataInputStream readShort() read() ... ... InputStream read() ... ...

  50. Source vs. Filter Streams • 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.

More Related