Class 29: Introduction To Streams - DSpace@MIT Home

3y ago
23 Views
2 Downloads
302.41 KB
16 Pages
Last View : 15d ago
Last Download : 3m ago
Upload by : Esmeralda Toy
Transcription

Introduction to Computation and ProblemSolvingClass 29:Introduction to StreamsProf. Steven R. LermanandDr. V. Judson HarwardGoalsJust as Java has a modern approach to errorhandling inherited from C , Java communicates with the outside world usinganother C inspired technique called streams.In this session, we will: Look at the classic stream code to read a file.Examine Java 's architecture of stream classesLearn how to parse simple text input.21

JFileViewer JFileViewer is a small demonstrationprogram that reads in reads in a file andputs it up in a text area. It is composed of two classes:– JFileViewer: main() and main loop– JTextViewer: the (rudimentary) GUI3JFileViewer,core try block (in English)try {open a stream from the filewhile there is more dataread itappend it to our GUI displayclose the file}catch any I/O errors42

JFileViewer,core try block (in Java )try {FileReader in new FileReader( args[ 0 ] );char [] buf new char[ 512 ];int nread;while( ( nread in.read( buf ) ) 0 ){ view.append( new String( buf, 0, nread ) ); }in.close();}catch ( IOException e ){handleErr( e );}5Traditional I/OThe traditional approach uses differentschemes depending on the type ofthe source or destination, e.g.,– keyboard input– screen output– files– interprocess pipes– network sockets63

Java I/O Java ’s preferred approach is to handle I/O usingstreams (pioneered in C ) Think of a stream as a data hose connecting theprogram to the outside world. It hides the details of the external data source ordestination. Java allows you to treat some I/O distinctively,e.g. RandomAccessFile7Input vs Output Streams Streams are unidirectional An input stream controls data coming intothe program from some source An output stream controls data leaving theprogram for some destination If you want to read and write the samedestination, you use 2 streams84

Streams and I/O ChannelsUsually the other end of a stream leads to orarises from a platform-specific mediaservice, for instance, a file systemOutput StreamInput StreamFileSystemProgramFileSystem9Java Stream ClassesJava provides– a set of abstract stream classes that define the streaminterfaces for different kinds of streams: InputStream: reads bytes OutputStream: writes bytes Reader: reads chars Writer: writes chars– a hierarchy of stream implementations: that are tailored for a particular data source ordestination, e.g., FileReader reads chars from a file that add functionality to a preexisting stream (filterstreams), e.g., BufferedReader105

What Streams Share Java Streams are FIFO queues– Streams deliver information in the orderit was inserted into the underlyingchannel Basic Java streams only providesequential access without rewind,backup, or random access11Coupling Streams Java streams may be combined by usingone stream as a constructor argument toanother This is usually done to add functionalityand/or convert the data Stream pipelines are constructed– from the data source to the program or– from the data destination back to the program126

Stream Pipeline, derTokenizer13Stream Pipeline, II A FileInputStream reads bytes from afile An InputStreamReader converts a bytestream to characters– A FileInputStream coupled with anInputStreamReader equals a FileReader A BufferedReader buffers a characterstream for efficiency, and alows you toread line by line A StreamTokenizer parses a characterstream into tokens147

Constructing the PipelineFileInputStream f new FileInputStream( path );InputStreamReader i new InputStreamReader( f );BufferedReader b new BufferedReader( i );StreamTokenizer t new StreamTokenizer( b );15The 3 Flavors of StreamsIn Java , you can read and write data to a file:– as text using FileReader and FileWriter– as binary data using DataInputStreamcoupled to a FileInputStream and as aDataOutputStream coupled to aFileOutputStream– as objects using an ObjectInputStreamcoupled to a FileInputStream and as anObjectOutputStream coupled to aFileOutputStream168

Text Streams: ReadersFileReader methods:– public FileReader(String name)throws FileNotFoundException– public FileReader(File f)throws FileNotFoundException– public int read(char[] cbuf) throws IOException– public int read() throws IOException– public void close() throws IOExceptionBufferedReader methods:– public BufferedReader(Reader in)– public String readLine() throws IOException17Text Streams: WritersFileWriter licFileWriter(String name) throws IOExceptionFileWriter(File f) throws IOExceptionvoid write(char[] cbuf) throws IOExceptionvoid write(String s) throws IOExceptionvoid write(int c) throws IOException– public void close() throws IOException– public void flush() throws IOExceptionBufferedWriter methods:– public BufferedWriter(Writer in)– public void newLine() throws IOException189

DataInputStream Methods– public DataInputStream(InputStream in), e.g.DataInputStream d new DataInputStream(new FileInputStream( "f.dat" ));– public boolean readBoolean() throws IOException– public int readInt() throws IOException– etcplus all the standard InputStream methods:– public int read() throws IOException– public int read(byte[] b) throws IOException– public int read(byte[] b, int off, int len)throws IOException– public void close() throws IOException19ObjectOutputStream Methods– public ObjectOutputStream(OutputStream out), e.g.ObjectOutputStream d new ObjectOutputStream(new FileOutputStream( "f.dat" ));– public void writeBoolean(boolean b) throwsIOException– public void writeInt(int i) throws IOException, etc– public void writeObject(Object obj) throwsIOExceptionplus all the standard OutputStream methods:– public void write(int i) throws IOException– public void write(byte[] b) throws IOException– public void write(byte[] b, int off, int len)throws IOException– public void close() throws IOException2010

Serialization ObjectInputStream and ObjectOutputStreamdepend on a technique called object serialization. If you want to write out an object instance on astream, you must write out the object's fields. The fields can contain native types or referencesto other object instances. You can recursively write out those references tocontained instances. Eventually you can serialize any object instance(from a class that implements Serializable)into fields of native types21Serialization DiagramLive ObjectsSerializedTypeA hdrTypeAintintdoubledoubleTypeBTypeB hdrintTypeBTypeA methodsintStringTypeBintintStringTypeB methods2211

Serializing a ListListfirstThe serialized version must preserve the informationthat the 1st and 3rd links are the same Date so we donot end up with 2 copies of DateA when the List is restored.lastLink 1Link 2DateADateBLink 3Link 4nullDateC23StreamTokenizer Java supplies a special class called StreamTokenizer thataccepts a Reader as a constructor argument.It breaks the input character stream into tokens, sequencesof 1 or more contiguous characters that "belong" together.The user accesses these tokens by calling thenextToken() method, which always returns an intrepresenting the type of the next token:– word,– number,– end of file (EOF),– end of line (EOL, optional), and– otherCharacter , returned as int value of the 16 bitcharacter code2412

StreamTokenizer, 2 When a StreamTokenizer recognizes a word,the public member sval contains the Stringrepresenting the word. When a number token is recognized, publicmember nval contains its value. StreamTokenizer also ignores whitespace(blanks and tabs) and C, C , and Java stylecomments by default. StreamTokenizer instance methods can changethe definition of “word” or “number” and canturn on or off features like ignoring comments.25JPolygonPlotter PolygonPlotter is a sample programthat illustrates how to handle formattedinput. It reads a data file that describes a set ofpolygons and then plots them in awindow. The command line accepts 3 arguments:width and height of the display windowand the name of the data file.2613

JPolygonPlotter, 2 The data file consists of a series of polygondefinitions separated by blank lines. Each polygon definition consists of linescontaining two integers each, an x- and a ycoordinate. The program checks for improperly formattedinput. If it can not make sense of what it isreading, it throws an DataFormatException. In the catch clause it sends an error message tothe console identifying where in the input file itgot confused.27JPolygonPlotter, main()public class PolygonPlotter {private static PolygonViewer view;private static int width 0;private static int height 0;private static FileReader fileRdr;public static void main( String[] args ) {. . .view new PolygonViewer( width, height );readPolygons( args[ 2 ] );. . .}2814

JPolygonPlotter, readPolygons()private static void readPolygons( String f ) {try {fileRdr new FileReader( f );BufferedReader bufRdr new BufferedReader( fileRdr );StreamTokenizer tokens new StreamTokenizer( bufRdr );tokens.eolIsSignificant( true );main loopbufRdr.close();} catch ( IOException e ) {handleErr( e );}}29JPolygonPlotter, readPolygons()main loop in Englishtry {get a tokenwhile we haven't reached the end of fileif line is blank, skip itelse if the line starts with a numberextract the next polygon from the dataelse throw a DataFormatException}} catch ( DataFormatException e ) {write an error message and exit}3015

JPolygonPlotter, readPolygons() mainlooptry {tokens.nextToken();while ( tokens.ttype ! StreamTokenizer.TT EOF ){if ( tokens.ttype StreamTokenizer.TT EOL ) {// if line is blank, skip ittokens.nextToken();} else if ( tokens.ttype StreamTokenizer.TT NUMBER ) {// if line starts with a number, parse polygonview.addPolygon( extractPolygon( tokens ));} elsethrow new DataFormatException();}} catch ( DataFormatException e ) {System.err.println( "Can't read polygon @ lineno " tokens.lineno() "." );System.exit( 1 );}31JPolygonPlotter, extractPolygons()private static Polygon extractPolygon( StreamTokenizer t )throws DataFormatException, IOException {Polygon p new Polygon();do {int x ( int ) t.nval;if ( t.nextToken() ! StreamTokenizer.TT NUMBER )throw new DataFormatException();int y ( int ) t.nval; y height - y - 1;if ( t.nextToken() StreamTokenizer.TT EOL t.ttype StreamTokenizer.TT EOF ) {p.addPoint( x, y );} else throw new DataFormatException();} while ( t.ttype StreamTokenizer.TT EOL &&t.nextToken() StreamTokenizer.TT NUMBER );return p;}32Java is a trademark or registered trademark of Sun Microsystems, Inc. in the UnitedStates and other countries.16

Java I/O Java ’s preferred approach is to handle I/O using streams (pioneered in C ) Think of a stream as a data hose connecting the program to the outside world. It hides the details of the external data source or destination. Java allows you to treat some I/O distinctively, e.g. RandomAccessFile 7 Input vs Output Streams Streams are unidirectional

Related Documents:

In HYSYS, there are two types of streams, Material and Energy . Material streams have a composition and parameters such as temperature, pressure and flow rate. They are used to represent Process Streams. Energy streams have only one parameter, Heat Flow. They represent heatin

Types of Streaming data Transaction streams credit card, point-of-sale transaction at a supermarket, or online purchase of an item Web click-streams Social streams online social networks such as Twitter speed and volume of the stream typically scale super-linearly with the number of actors Network streams

Router, Forms, Unit Testing, Migration to Angular 2. AngularConnect - Sept 27-28th @AngularConnect. Asynchronous Data Streams. Streams Asynchronous, register a callback to be notified when results are available Data, raw information: Number, String, Objects (Arrays, Sets, Maps) Streams, sequences of data made

the Stream visible by selecting the "Eye" icon at the left of the new Stream row. The Stream tabbed dialog appears at the bottom of the application window. Tip: You can manage existing Streams and global Streams options from the Streams List dialog. Add Layer Type checks to your new Stream using the Add New Check icon in the

IBM InfoSphere Streams V3.0 Mike Ebbers Ahmed Abdel-Gayed Veera Bhadran Budhi Ferdiansyah Dolot Vishwanath Kamat Ricardo Picone João Trevelin Performing real-time analysis on big data by using System x Developing a drag and drop Streams application Monitoring and administering Streams.

- don't use same seed for 2 or more streams! —if seeds are bad, streams will overlap and not be independent —right way: select seeds so streams don't overlap at all - example: need 3 streams of 20,000 numbers pick u0 as seed for first stream pick u20,000 as seed for second stream pick u40,000 as seed for third stream

work/products (Beading, Candles, Carving, Food Products, Soap, Weaving, etc.) ⃝I understand that if my work contains Indigenous visual representation that it is a reflection of the Indigenous culture of my native region. ⃝To the best of my knowledge, my work/products fall within Craft Council standards and expectations with respect to

Here are a few suggested references for this course, [12,15,1]. The latter two references are downloadable if you are logging into MathSci net through your UCSD account. For a proof that all p{ variation paths have some extension to a rough path see, [14] and also see [6, Theorem 9.12 and Remark 9.13]. For other perspectives on the the theory, see [3] and also see Gubinelli [7,8] Also see, [9 .