1 streams chapter nineteen. 2 what are streams? l input and output for example from the keyboard (a...

47
Streams Streams Chapter Nineteen

Upload: lewis-preston

Post on 18-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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

1

StreamsStreams

Chapter Nineteen

Page 2: 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

2

What are streams?What are streams?

Input and Output for example from the keyboard (a standard input device) or the CRT (a standard output device) or I/O with files.

TOPICS: Input streams how to create, use, detect

end of them and filtered input streams Output streams mostly opposite of input

Page 3: 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

3

Some terms:Some terms:

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

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.

Page 4: 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

4

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

Page 5: 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

5

Input StreamsInput Streams

Methods used are “throw IOExceptions”– subclass “Exception”

You must catch an IOException (or pass it along)

The abstract Class InputStream - You are the destination of the bytes - do not care where they came from

Page 6: 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

6

read( ) “block” - wait for the input requested [ a good chance to use multi threading while you wait ]

InputStream s = getAnInputStreamFromSomewhere( );

byte[] buffer = new byte[1024]; // any size

if(s.read(buffer) ! = buffer.length) System.out.println(“I got less than I

expected.”); //In this chapter an import

java.io.*should be at top of all programs

Page 7: 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

7

What the last program will What the last program will do.do.Either it will fill the entire Either it will fill the entire buffer or it will return buffer or it will return thenumber of bytes read thenumber of bytes read into the buffer.into the buffer. Another possible use of read( ) s.read(buffer, 100,300); // start

with an offset (up from beginning 100 bytes) and then go for 300 bytes.

Page 8: 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

8

Example: public int read(byte[] buffer) throws

IOException { return read(buffer, 0, buffer.length); } InputStream s =

getAnInputStreamFromSomewhere( ); byte b; int byteOrMinus1; while ((byteOrMinus = s.read( )) != -1) { b = (byte) byteOrMinus1; .... //process

the // byte b } ... reached end of stream NOTE the read( ) method return an

integer

Page 9: 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

9

skip( ) how it can be skip( ) how it can be used - kind of like a read( )used - kind of like a read( ) if (s.skip(1024) ! = 1024) System.out.println(“I skipped less

that I expected.”);

public long skip(long n) throws IOException {

byte[] buffer = new byte [ (int) n]; return read(buffer); } // NOTE (int)

Page 10: 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

10

available( ) - How many available( ) - How many bytes are in the stream?bytes are in the stream? if (s.available( ) < 1024) System.out.println(“Too little is

available right now.”); problem: way some streams

always return zero when asked and because of multithreading - no need for available( )

Page 11: 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

11

mark( ) and reset( )mark( ) and reset( )

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

InputStream s = getAnInputStreamFromSomewhere( );

if(s.markSupported( )) //read for awhile s.mark(1024); ... s.reset( ); } else ...

{... }

Page 12: 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

12

close( )close( )

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.

A good way of making sure: InputStream s =

alwaysMakesANewInputStream( ); try { ...// use s to your hearts content } finally { s.close( ); }

Page 13: 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

13

even better InputStream s =

tryToMAkeANewInputStream( ); if( s != null) { try { ... } // just in

case a null was returned finally { s.close( ); } }

Page 14: 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

14

ByteArrayInputStreamByteArrayInputStream

Purpose to create a stream from an array of bytes // kind of the reverse of what previous slides have been discussing:

byte[] buffer = new byte[1024]; fillWithUsefulDate(buffer); InputStream s = new

ByteArrayInputStream(buffer); like read( ) // has a form with offset and

length

Page 15: 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

15

InputStream s = new ByteArrayInputStream(buffer, 100, 300);

Creates a Stream... available( ) reset( ) can be used

too.

Page 16: 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

16

FileInputStreamFileInputStream

InputStream s = new FileInputStream (“/some/path/and/filename”);

This MAY cause security violations (applets reading or attempting to read files set off all kinds of ALARMS (sometimes)

You should keep it short: The user may assign a single file/directory with permission attached to it

Page 17: 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

17

You can create a stream You can create a stream from a previously opened from a previously opened file descriptor:file descriptor: int fd =

openInputFileInTraditionalUNIXWays( ); InputStream s = new

FileInputStream(fd); Some additional tricks: FileInputStream aFIS = new

FileInputStream(“aFIleName”); int myFD = aFIS.getFD( ); /* aFIS.finalize( ); */ // will call close( )

Page 18: 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

18

FilterInputStreamFilterInputStream

The general idea a “filter” or pass through InputStream s =

getAnInputStreamFromSomewhere( ); FilterInputStream s1 = new

FilterInputStream(s); FilterInputStream s2 = new

FilterInputStream(s1); FilterInputStream s3 = new

FilterInputStream(s2); ...s3.read( ) ...

Page 19: 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

19

How the last slide (code) How the last slide (code) worksworks the read s3 passes onto s2 inturn

to s1 and finally to s. s is asked for the bytes

also called “chaining” Example of filters (ie. little rocks

go through big ones do not) pass through account ...

Page 20: 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

20

BufferedInputStreamBufferedInputStream one of Most valuable: reads “chunks” 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.

handels mark( ) reset( ) properly and you can mark/reset files (which are

streams....of course....at least the data in them can be:

InputStream s = new BufferedInputStream(new FIleInputStream(“foo”));

Page 21: 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

21

DataInputStreamDataInputStream A general purpose interface (you can use

it in the classes you create) DataInputStream and RandomAccessFile implement. The DataInput Interface: SEE PAGE 385 for

all the methods this interface defines: General form: read....( ) boolean, byte,short,int(signed/unsigned, char,long,float,double,String(Line/UTF ALL throw IOExceptions

Page 22: 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

22

Example of last slideExample of last slide DataInputStream s = new

DataInputStream(getNumericInputStream( )); long size = s.readLong( );

while (size >0) { if (s.readBoolean( ) ) { int anInteger = s.readInt( ); int magicBitFlags =

s.readUnsignedShort( ); double aDouble = s.readUnsignedShort( ); if ((magicBitFlags & 0100000) ! = 0) { ... // hi bit set, do something}...//process }

}

Page 23: 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

23

EOFException = end of EOFException = end of file (stream) exceptionfile (stream) exception DataInputStream s = new

DataInStream(getAISFS( )); // abbreviation

try { while (true) { byte b = (byte) s.readByte( ); ..// process byte } catch

(EOFException e) { //... reached end of //stream

}

Page 24: 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

24

LineNumberInputStream:LineNumberInputStream:

Streams with line numbers (listings etc.) mark( ) it and reset( ) it later

a variable called aLNIS (line number input file/stream) is checked

The system print “did line number + aLNIS.getLineNumber( ));

Page 25: 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

25

PushbackInputStreamPushbackInputStream

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

\n legal escape sequence in Java C C++

Page 26: 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

26

//unread( ) does the “pushback” (i.e. read a character - then go back one after “you” figure what to do next: Example

public class SimpleLineReader { private FilterInputStream s; public SimpleReader(InputStream anIS)

{ a = new DataInputStream(anIS); } public String readLine( ) throws

IOException { char[] buffer = new char[100]; byte thisbyte; // ONLY 100

Page 27: 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

27

try { // note next line “loop:” = top of loop // first example in text loop: while (offset < buffer.length) { switch (thisByte = (byte) s.read( ); // good quiz question why (byte) in last

line case ‘\n’: break loop; case ‘\r’ : byte nextByte = (byte) s.read( ); if (nextByte ! = ‘\n’) {

– if (!( s instanceof PushbackInputStream)) {– s = new PushbackInputStream(s) ; }– ( (PushbackInputStream) s).unread(nextByte);

Page 28: 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

28

if (nextByte ! = ‘\n’) {– if (!( s instanceof PushbackInputStream)) {– s = new PushbackInputStream(s) ; }– ( (PushbackInputStream)

s).unread(nextByte); } // Note unread( ) break loop; default: buffer[offset++] = (char)

thisByte; break: } } } catch (EOFException e) { if (offfset = = 0) return null; } return

String.copyValueOf(buffer, 0, offset); } }

Page 29: 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

29

PipedInputStream / PipedInputStream / PipedOutputStream two PipedOutputStream two way Communication way Communication between threadsbetween threads How to Concatenate two Streams: Good bye ---> Goodbye InputStream s1 = new

FileInputStream(“theFirstPart”);

Page 30: 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

30

InputStream s2 = new FileInputStream”theRest”);

InputStream s = new SequenceInputStream(s1 s2);

s.read( ) ... reads from s the combined stream

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

Page 31: 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

31

StringBufferInputStreamStringBufferInputStream

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”

String buffer = “ Now is the time ...etc”;

InputStream s = new StringBufferInputStream(buffer)

Acts like ByteArrayInputStream

Page 32: 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

32

Output Streams Or... We Output Streams Or... We have ways of making you have ways of making you talk....talk.... Who you are really talking to is irrelevant You control the vertical You control the

horizontal...Just kidding...You actually control the bytes: write( ) Example:

OutputStream s = getAnOutputStreamFromSomewhere( );

byte[] buffer = new byte[1024]; //any size fillInData(buffer); s.write(buffer); OR s.write(buffer, 100, 300); // put it exactly...

Page 33: 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

33

Do not forget to flush( ) Do not forget to flush( ) and close( ) That and close( ) That sounds awful...but it may sounds awful...but it may NOT be a bad thing...NOT be a bad thing... flush( ) = send your output

through some buffer close( ) = release resources that

may have been reserved for your behalf

Page 34: 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

34

ByteArrayOutputStream ByteArrayOutputStream directs an output stream directs an output stream INTO an array of bytesINTO an array of bytes OutputStream s = new

ByteArrayOutputStream( ); ....s.write(123); You can add an initital capacity by: OutputStream s = new

ByteArrayOutputStream(1024 * 1024); Stream can be output (re-directed) to

another stream

Page 35: 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

35

FileOutputStreamFileOutputStreamUSE: attach the stream to USE: attach the stream to file(s)file(s) OutputStream s = new

FileOutputStream(“/some/path/and/filename”);

CAN cause security violations on some systems

Page 36: 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

36

FilterOutputStreamFilterOutputStream

A pass-through abstract class (a pass through account is supposed to

be temporary - several checks deposited to it one written out)

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

Page 37: 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

37

BufferedOutputStreamBufferedOutputStream

Acts as a cache (pronounced cash $ ) decouples (breaks down) chunks

rate/size blocks into more efficient data size for peripherals/files/or the net

OutputStream s = new BufferedOutputStream( new FileOutputStream(“foo”));

flush( ) // is then possible

Page 38: 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

38

DataOutputStream DataOutputStream Similar but opposite side Similar but opposite side on coin of “DataInput” on coin of “DataInput” interfaceinterface DataOutputStream and RandomAccessFile

implement - general purpose The DataOutput Interface covers: ( int i), (byte[] buffer) (byte[] buffer, int

offset, int length) writeBoolean, Byte, Short, Char, Int, Long,

Float, Double, Bytes, Chars, and writeUTF All throw IOExceptions

Page 39: 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

39

Quick example:Quick example:

DataOutputStream s = new DataOutputStream(getNumericOutputStream( ) ); long size = getNumberOfItemsInNumericStream( );

s.writeLong(size); for (int i = 0; i < size; ++i) {

– if (shouldProcessNumber(i) ) {

Page 40: 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

40

s.writeBoolean(true); s.writeInt(theIntegerForOtemNumber(i)

); s.writeShort(theMagicBitFlagsForNume

r(i)); s.writeDouble(theDoubleForInemNumber(i)); } else

s.writeBoolean(false); } THIS example is the exact inverse of

DataInput both communicate an array of structures primitive types accross any stream. (SLIDE 22)

Page 41: 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

41

Processing a file (read/process a record/write out to a different file)

DataInput aDI = new DataInputStream(new FileINputStream(“source”));

DataOutput aDO = new DataOutputStream(new FileOutputStream(“dest”));

String line; // all the major variables aDI, aDO,

line

Page 42: 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

42

while ((line = aDI.readLine( ) ) ! = null) {

// Not E.O.L. yet StringBuffer modifiedLine = new

StringBuffer(line); ...// do some process aDO.writeBytes(modifiedLine.toStri

ng( ) );} aDI.close( ); aDO.close( );

// remember to close....

Page 43: 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

43

//just a few lines more... try {

– while(true) {– byte b = (byte) aDI.readByte( );– ... // process b here – aDO.writeByte(b) }

finally { aDI.close; aDO.close( ); }

OR... try { while (true) aDO.writeByte(aDI.readByte( ) );}

finally { aDI.close( ); aDO.clase( ); }

Page 44: 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

44

Streams you have already Streams you have already crossed...crossed... System.out.print( ) System.out.println( ) System.err // not that anyone

ever has err System.in // input stream

Page 45: 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

45

See page 398 for all the See page 398 for all the choices of primitive type choices of primitive type (some 23 examples)(some 23 examples)

// Just one here

public void printl(int i);

Page 46: 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

46

PipedOutputStream - PipedOutputStream - along with along with PipedInputStream PipedInputStream supports piped supports piped connections between two connections between two threadsthreads

PipedInputStream sIN = PipedInputStream( );

PipedOutputStream sOut = PipedOutputStream(sIn); // that s - In

not //sin....One thread writes to sOut the other reads from sIn

Page 47: 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

47

Related ClassesRelated Classes

File // tells about attributes of specific file

RandomAccessFile // provides “seek( )ing

StreamTokenizer class // tokens ie words seperated by any thing you decide