Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Streams Chapter Nineteen. 2 What are streams? l Input and Output for example from the keyboard (a standard input device) or the CRT (a standard output.

Similar presentations


Presentation on theme: "1 Streams Chapter Nineteen. 2 What are streams? l Input and Output for example from the keyboard (a standard input device) or the CRT (a standard output."— Presentation transcript:

1 1 Streams Chapter Nineteen

2 2 What are streams? l Input and Output for example from the keyboard (a standard input device) or the CRT (a standard output device) or I/O with files. l TOPICS: l Input streams how to create, use, detect end of them and filtered input streams l Output streams mostly opposite of input

3 3 Some terms: l Pipe - an uninterpreted stream of bytes. Communication between programs are for reading/writing to peripheral devices. The stream can come from any source your disk or the internet as examples l UNIX an operating system (CCAC uses a UNIX server for its internet server) it will be the location of your web pages called a point server.

4 4 InputStream and OutputStream are java abstract classes...See java.io (Appendix B). Text starts at the top of the tree and works down All program sequences this chapter need Import java.io.*;

5 5 Input Streams l Methods used are “throw IOExceptions” –subclass “Exception” l You must catch an IOException (or pass it along) l The abstract Class InputStream - You are the destination of the bytes - do not care where they came from

6 6 l read( ) “block” - wait for the input requested [ a good chance to use multi threading while you wait ] l InputStream s = getAnInputStreamFromSomewhere( ); l byte[] buffer = new byte[1024]; // any size l if(s.read(buffer) ! = buffer.length) l System.out.println(“I got less than I expected.”); l //In this chapter an import java.io.*should be at top of all programs

7 7 What the last program will do. Either it will fill the entire buffer or it will return thenumber of bytes read into the buffer. l Another possible use of read( ) l s.read(buffer, 100,300); // start with an offset (up from beginning 100 bytes) and then go for 300 bytes.

8 8 l Example: l public int read(byte[] buffer) throws IOException { l return read(buffer, 0, buffer.length); } l InputStream s = getAnInputStreamFromSomewhere( ); l byte b; int byteOrMinus1; l while ((byteOrMinus = s.read( )) != -1) { l b = (byte) byteOrMinus1;.... //process the // byte b }... reached end of stream l NOTE the read( ) method return an integer

9 9 skip( ) how it can be used - kind of like a read( ) l if (s.skip(1024) ! = 1024) l System.out.println(“I skipped less that I expected.”); l public long skip(long n) throws IOException { l byte[] buffer = new byte [ (int) n]; l return read(buffer); } // NOTE (int)

10 10 available( ) - How many bytes are in the stream? l if (s.available( ) < 1024) l System.out.println(“Too little is available right now.”); l problem: way some streams always return zero when asked and because of multithreading - no need for available( )

11 11 mark( ) and reset( ) l Have you ever marked your way (or some line of code in a trace?) I am Here NOW...later reset(ing) back to the original position. You set the bytes you can go before reset(ing): l InputStream s = getAnInputStreamFromSomewhere( ); l if(s.markSupported( )) //read for awhile l s.mark(1024);... s.reset( ); } else... {... }

12 12 close( ) l Some systems if you do not close files they just stay open and are at the mercy (do not count on mercy) of anyone on the system - which may be the internet. l A good way of making sure: l InputStream s = alwaysMakesANewInputStream( ); l try {...// use s to your hearts content l } finally { s.close( ); }

13 13 l even better l InputStream s = tryToMAkeANewInputStream( ); l if( s != null) { try {... } // just in case a null was returned l finally { s.close( ); } }

14 14 ByteArrayInputStream l Purpose to create a stream from an array of bytes // kind of the reverse of what previous slides have been discussing: l byte[] buffer = new byte[1024]; l fillWithUsefulDate(buffer); l InputStream s = new ByteArrayInputStream(buffer); l like read( ) // has a form with offset and length

15 15 l InputStream s = new ByteArrayInputStream(buffer, 100, 300); l Creates a Stream... l available( ) reset( ) can be used too.

16 16 FileInputStream l InputStream s = new FileInputStream (“/some/path/and/filename”); l This MAY cause security violations (applets reading or attempting to read files set off all kinds of ALARMS (sometimes) l You should keep it short: The user may assign a single file/directory with permission attached to it

17 17 You can create a stream from a previously opened file descriptor: l int fd = openInputFileInTraditionalUNIXWays( ); l InputStream s = new FileInputStream(fd); l Some additional tricks: l FileInputStream aFIS = new FileInputStream(“aFIleName”); l int myFD = aFIS.getFD( ); l /* aFIS.finalize( ); */ // will call close( )

18 18 FilterInputStream l The general idea a “filter” or pass through l InputStream s = getAnInputStreamFromSomewhere( ); l FilterInputStream s1 = new FilterInputStream(s); l FilterInputStream s2 = new FilterInputStream(s1); l FilterInputStream s3 = new FilterInputStream(s2);...s3.read( )...

19 19 How the last slide (code) works l the read s3 passes onto s2 inturn to s1 and finally to s. s is asked for the bytes l also called “chaining” l Example of filters (ie. little rocks go through big ones do not) l pass through account...

20 20 BufferedInputStream l one of Most valuable: reads “chunks” l A buffer is memory for example that is used as an area that “spoon feeds” a peripherial device at its speed not full speed of CPU. l handels mark( ) reset( ) properly l and you can mark/reset files (which are streams....of course....at least the data in them can be: l InputStream s = new BufferedInputStream(new FIleInputStream(“foo”));

21 21 DataInputStream l A general purpose interface (you can use it in the classes you create) l DataInputStream and RandomAccessFile l implement. l The DataInput Interface: SEE PAGE 385 for all the methods this interface defines: l General form: read....( ) l boolean, byte,short,int(signed/unsigned, l char,long,float,double,String(Line/UTF l ALL throw IOExceptions

22 22 Example of last slide l DataInputStream s = new DataInputStream(getNumericInputStre am( )); long size = s.readLong( ); l while (size >0) { if (s.readBoolean( ) ) { l int anInteger = s.readInt( ); l int magicBitFlags = s.readUnsignedShort( ); l double aDouble = s.readUnsignedShort( ); l if ((magicBitFlags & 0100000) ! = 0) { l... // hi bit set, do something}...//process } }

23 23 EOFException = end of file (stream) exception l DataInputStream s = new DataInStream(getAISFS( )); // abbreviation l try { while (true) { byte b = (byte) s.readByte( );..// process byte } catch l (EOFException e) { //... reached end of //stream l }

24 24 LineNumberInputStream: l Streams with line numbers (listings etc.) mark( ) it and reset( ) it later l a variable called aLNIS (line number input file/stream) is checked l The system print “did line number + aLNIS.getLineNumber( ));

25 25 PushbackInputStream l a look ahead (C/C++ think escape sequences) OK we found a \ look ahead see if next character is a legal escape character if OK do “it” else ERROR caused l \n legal escape sequence in Java C C++

26 26 l //unread( ) does the “pushback” (i.e. read a character - then go back one after “you” figure what to do next: Example l public class SimpleLineReader { l private FilterInputStream s; l public SimpleReader(InputStream anIS) { l a = new DataInputStream(anIS); } l public String readLine( ) throws IOException { char[] buffer = new char[100]; byte thisbyte; // ONLY 100

27 27 l try { // note next line “loop:” = top of loop l // first example in text l loop: while (offset < buffer.length) { l switch (thisByte = (byte) s.read( ); l // good quiz question why (byte) in last line l case ‘\n’: break loop; l case ‘\r’ : byte nextByte = (byte) s.read( ); l if (nextByte ! = ‘\n’) { –if (!( s instanceof PushbackInputStream)) { –s = new PushbackInputStream(s) ; } –( (PushbackInputStream) s).unread(nextByte);

28 28 l if (nextByte ! = ‘\n’) { –if (!( s instanceof PushbackInputStream)) { –s = new PushbackInputStream(s) ; } –( (PushbackInputStream) s).unread(nextByte); } // Note unread( ) l break loop; l default: buffer[offset++] = (char) thisByte; l break: } } } l catch (EOFException e) { if (offfset = = 0) l return null; } return String.copyValueOf(buffer, 0, offset); } }

29 29 PipedInputStream / PipedOutputStream two way Communication between threads l How to Concatenate two Streams: l Good bye ---> Goodbye l InputStream s1 = new FileInputStream(“theFirstPart”);

30 30 l InputStream s2 = new FileInputStream”theRest”); l InputStream s = new SequenceInputStream(s1 s2); l s.read( )... reads from s the combined stream l The same idea can continue to work with more than two Strings...first InputStream the first two then the third with the result of the combination of S1 and S2... and that could go on...and on...

31 31 StringBufferInputStream l based on an array of characters: –If a buffer was filled with “Now is the time for all good men to come to the aid of their party” l String buffer = “ Now is the time...etc”; l InputStream s = new StringBufferInputStream(buffer) l Acts like ByteArrayInputStream

32 32 Output Streams Or... We have ways of making you talk.... l Who you are really talking to is irrelevant l You control the vertical You control the horizontal...Just kidding...You actually control the bytes: write( ) Example: l OutputStream s = getAnOutputStreamFromSomewhere( ); l byte[] buffer = new byte[1024]; //any size l fillInData(buffer); s.write(buffer); OR l s.write(buffer, 100, 300); // put it exactly...

33 33 Do not forget to flush( ) and close( ) That sounds awful...but it may NOT be a bad thing... l flush( ) = send your output through some buffer l close( ) = release resources that may have been reserved for your behalf

34 34 ByteArrayOutputStream directs an output stream INTO an array of bytes l OutputStream s = new ByteArrayOutputStream( );....s.write(123); l You can add an initital capacity by: l OutputStream s = new ByteArrayOutputStream(1024 * 1024); l Stream can be output (re-directed) to another stream

35 35 FileOutputStream USE: attach the stream to file(s) l OutputStream s = new FileOutputStream(“/some/path/and/f ilename”); l CAN cause security violations on some systems

36 36 FilterOutputStream l A pass-through abstract class l (a pass through account is supposed to be temporary - several checks deposited to it one written out) l like FilterInputStream just passes requests for a write( ) up a chain - sme minor processing may be done: s3.write(123) in example passed to s2, s2 and finally s

37 37 BufferedOutputStream l Acts as a cache (pronounced cash $ ) l decouples (breaks down) chunks rate/size blocks into more efficient data size for peripherals/files/or the net l OutputStream s = new BufferedOutputStream( new FileOutputStream(“foo”)); l flush( ) // is then possible

38 38 DataOutputStream Similar but opposite side on coin of “DataInput” interface l DataOutputStream and RandomAccessFile implement - general purpose l The DataOutput Interface covers: l ( int i), (byte[] buffer) (byte[] buffer, int offset, int length) l writeBoolean, Byte, Short, Char, Int, Long, Float, Double, Bytes, Chars, and writeUTF l All throw IOExceptions

39 39 Quick example: l DataOutputStream s = new DataOutputStream(getNumericOutput Stream( ) ); long size = getNumberOfItemsInNumericStream( ); l s.writeLong(size); l for (int i = 0; i < size; ++i) { –if (shouldProcessNumber(i) ) {

40 40 l s.writeBoolean(true); l s.writeInt(theIntegerForOtemNumber(i) ); l s.writeShort(theMagicBitFlagsForNume r(i)); s.writeDouble(theDoubleForInemNum ber(i)); } else l s.writeBoolean(false); } l THIS example is the exact inverse of DataInput both communicate an array of structures primitive types accross any stream. (SLIDE 22)

41 41 l Processing a file (read/process a record/write out to a different file) l DataInput aDI = new DataInputStream(new FileINputStream(“source”)); l DataOutput aDO = new DataOutputStream(new FileOutputStream(“dest”)); l String line; l // all the major variables aDI, aDO, line

42 42 l while ((line = aDI.readLine( ) ) ! = null) { l // Not E.O.L. yet l StringBuffer modifiedLine = new StringBuffer(line); l...// do some process l aDO.writeBytes(modifiedLine.toString( ) );} aDI.close( ); aDO.close( ); l // remember to close....

43 43 l //just a few lines more... l try { –while(true) { –byte b = (byte) aDI.readByte( ); –... // process b here –aDO.writeByte(b) } l finally { aDI.close; aDO.close( ); } l OR... try { while (true) aDO.writeByte(aDI.readByte( ) );} l finally { aDI.close( ); aDO.clase( ); }

44 44 Streams you have already crossed... l System.out.print( ) l System.out.println( ) l System.err // not that anyone ever has err l System.in // input stream

45 45 See page 398 for all the choices of primitive type (some 23 examples) l // Just one here l public void printl(int i);

46 46 PipedOutputStream - along with PipedInputStream supports piped connections between two threads l PipedInputStream sIN = PipedInputStream( ); l PipedOutputStream sOut = PipedOutputStream(sIn); // that s - In l not //sin....One thread writes to sOut the other reads from sIn

47 47 Related Classes l File // tells about attributes of specific file l RandomAccessFile // provides “seek( )ing l StreamTokenizer class // tokens ie words seperated by any thing you decide


Download ppt "1 Streams Chapter Nineteen. 2 What are streams? l Input and Output for example from the keyboard (a standard input device) or the CRT (a standard output."

Similar presentations


Ads by Google