O interfaces ports (serial port, parallel port, keyboard port, audio port, video port, SCSI port

EE 497 Java Programming To be covered 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 I/O Software Layers .......................................
Author: Cory Merritt
1 downloads 0 Views 203KB Size
EE 497 Java Programming

To be covered 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

I/O Software Layers .........................................................................................................................1 I/O Software Layers .........................................................................................................................1 What is a stream?..............................................................................................................................2 Stream Fundamentals .......................................................................................................................3 Stream Categories.............................................................................................................................3 Java Stream Classes..........................................................................................................................3 InputStreams.....................................................................................................................................4 OutputStreams ..................................................................................................................................5 Reader...............................................................................................................................................6 Reading from files ........................................................................................................................7 Stream Reader/Writer Classes ......................................................................................................7 Filtered Streams............................................................................................................................7 Buffered Streams ..........................................................................................................................8 Concatenating two Streams ..........................................................................................................8 DataInputStream / Data OutputStream .........................................................................................8 PrintStream & PrintWriter............................................................................................................9 ObjectOutputStream/ ObjectInputStream.....................................................................................9 Java’s File Management Methods ..............................................................................................10 Reading Files ..............................................................................................................................10 RandomAccessFile .....................................................................................................................10 Tokenizing Input Streams...........................................................................................................11

1

I/O Software Layers



Input ⇒Processing⇒Output



Built-in or peripheral I/O interfaces – ports (serial port, parallel port, keyboard port, audio port, video port, SCSI port.



Used to connect I/O devices such as modems, video, etc.

2

I/O Software Layers



Device driver – In order to shield the application from the ever-evolving programming model of an I/O device.



However, device drivers may need to be changed themselves!



Generic Device Independent I/O Devices: An extra layer of software in order to protect the application from the evolution of the device drivers themselves! (Different Operating Systems)



Final layer – In order to shield from different I/O systems.



The java.io package contains classes that perform input and output.

1

EE 497 Java Programming

• • •



3

In Java, I/O classes are differentiated according to the type of data being read or written. Byte oriented and numeric data is written with output streams and read with input streams. Character data, that is text, is written with writers and read with readers. Readers and writers operate much like streams but understand how to convert to and from various external character sets like Big-5 Chinese or MacRoman into Unicode. Whether you use streams or readers and writers depends on the type of data you're dealing with. In Java 1.1 and later all text data, especially non-ASCII text, should be passed through a reader or writer.

What is a stream?



Java IO is based on streams – sequences of bytes that travel from a source to a destination over a communication path.



A stream is a sequence of data of undetermined length. It's called a stream because it's like a stream of water that continues to flow. There's no definite end to it.



In Java a stream is composed of discrete bytes. The bytes may represent chars or other kinds of data. They may come faster than you can handle them, or your thread may block while waiting for the next one to arrive. It often doesn't matter.



The key to processing the stream is a while loop that processes each piece of data, until you encounter the end-of-stream character or some other exceptional condition occurs. In Unix you type end-of-stream with Control-D. On Windows, you type end-of-stream with Control-Z.



Abstract away the details of the communication path from the I/O details.



The two main stream classes are: o java.io.InputStream and java.io.OutputStream.



The two main reader and writer classes are: o



java.io.Reader and java.io.Writer

These are abstract base classes for many different subclasses with more specialized abilities.

2

EE 497 Java Programming

4

Stream Fundamentals



Software streams – Linear flows of data



Every stream •

If your program is writing to a stream – It is the stream’s source.



If your program is reading from a stream – It is the stream’s destination.



Source - Input stream - Should be connected to a device producing data.



Sink – Output stream-Should be connected to a device accepting data



Streams of bytes - InputStream & OutputStream



Streams of chars - Reader & Writer

5

Stream Categories



Node Streams - Read or write from a specific place such as a disk file or from memory



Filter streams - Connection to an already existing stream.

6

Java Stream Classes •

java.io.



InputStream o

FileInputStream

o

ByteArrayInputStream

o

FilterInputStream ƒ BufferedInputStream ƒ DataInputStream ƒ LineNumberInputStream ƒ PushbackInputStream ObjectInputStream PipedInputStream SequenceInputStream StringBufferInputStream

o o o o •

OutputStream o

FileOutputStream

3

EE 497 Java Programming

o o





• • • • • • • •

ByteArrayOutputStream FilterOutputStream ƒ BufferedOutputStream ƒ DataOutputStream ƒ PrintStream ObjectOutputStream PipedOutputStream

o o Reader o BufferedReader o CharArrayReader o FilterReader o InputStreamReader o PipedReader o StringReader Writer o BufferedWriter o CharArrayWriter o FilterWriter o OutputStreamWriter o PipedWriter o PrintWriter o StringWriter File RandomAccessFile FileDescriptor FilePermission ObjectStreamClass ObjectStreamField SerializablePermission StreamTokenizer

7

InputStreams



Read bytes of data from some kind of data source.



Byte-by-byte basis on blocks of arbitrary length.



Abstract Class -- Classes descending from InputStream •

FileInputStream - Data Source is a file.



ByteArrayInputStream



StringBufferInputStream



SequenceInputStream



PipedInputStream - Data source is a pipe



ObjectInputStream

4

EE 497 Java Programming





FilterInputStream - Data source is another input stream. •

BufferedInputStream



DataInputStream



LineNumberInputStream



PushbackInputStream

Common Feature •

Their constructors require the specification of a data source.

FileInputStream inStream = new FileInputStream("test.txt"); •

Methods • • • •

int available() – Returns the number of bytes available. int read() - Single byte int read(byte[]) - A byte array and returns the number of bytes read int read(byte[], int,int) - A byte array where only the specified range is filled.

byte inBuf[] = new byte[inBytes]; int bytesRead = inStream.read(inBuf,0,inBytes); •

close() - Should always close the stream once done.



Markable streams – Provide the capability to mark a position in the stream and then reset the stream so it can be read from the marked position. •

mark(), reset(), markSupported()



markSupported() - All streams should implement markSupported(), but are free to return true or false.



If mark feature is supported, you can mark any position to come back if one wants to undo the reading of data since the mark. • readlimit argument - specifies how far you can read.



reset() - com back to the mark position.



If one reads past the readlimit and then resets, the results are undefined.

Class Exercise: 8

OutputStreams

• •

java.io.OutputStream

This class sends raw bytes of data to a target such as the console or a network server.

5

EE 497 Java Programming



Like InputStream, OutputStream is an abstract class.



Subclasses are used • • • • • • • •

FilterOutputStream BufferedOutputStream DataOutputStream PrintStream ByteArrayOutputStream FileOutputStream ObjectOutputStream PipedOutputStream

FileOutputStream outStream = new FileOutputStream("test.txt");



Furthermore, many of the methods of OutputStream are generally useful. These are: public abstract void write(int b) throws IOException public void write(byte[] data) throws IOException public void write(byte[] data, int offset, int length) throws IOException public void flush() throws IOException public void close() throws IOException



The write() methods send raw bytes of data to whomever is listening to this stream.

String s = "This is a test."; outStream.write(s.getBytes());



Sometimes output streams are buffered by the operating system for performance. In other words, rather than writing each byte as it's written the bytes are accumulated in a buffer ranging from several bytes to several thousand bytes. Then, when the buffer fills up, all the data is written at once. The flush() method forces the data to be written whether or not the buffer is full.



This is not the same as the buffering performed by a BufferedOutputStream. That buffering is handled by the Java runtime. This buffering is at the native OS level. However, a call to flush() should empty both buffers



The close() method closes the stream and releases any resources associated with the stream. Once the stream is closed attempts to write to it throw IOExceptions

Class Exercise:

9 •

Reader Read streams of characters. •

FileReader



CharArrayReader

6

EE 497 Java Programming



StringReader



PipedReader



InputStreamReader



FilterReader • • •

BufferedReader LineNumberReader PushbackReader

10 Reading from files •

FileInputStream & FileReader



Both have a file as their source



Constructor arguments • • •

String File FileDescriptor

11 Stream Reader/Writer Classes ByteArrayInputStream & ByteArrayOutputStream StringBufferInputStream StringReader CharArrayReader & CharArrayWriter •

Create input(output) streams from either an array of bytes (byte buf[ ] ) or a String (arrays of chars -16bit wide Unicode characters)



Data source is either a char array (char chars[ ] or String s)



For data wider than 8 bits, the higher byte is discarded!



Difference btw ByteArrayInputStream & StringBufferInputStream - Input data source may be modified at any time in the first.

12 Filtered Streams FilterInputStream & FilterReader / FilterOutputStream & FilterWriter •

SUPERCLASS: FilterInputStream ⇔ FilterReader (Not for instantiation!)

7

EE 497 Java Programming

• • • • •

BufferedInputStream ⇔ BufferedReader DataInputStream LineNumberInputStream ⇔ LineNumberReader PushbackInputStream ⇔ PushbackReader

SUPERCLASS: FilterOutputStream ⇔ FilterWriter (Not for instantiation!) • • •

BufferedOutputStream ⇔ DataOutputStream PrintStream ⇔ PrintWriter

BufferedWriter

13 Buffered Streams BufferedInputStream ⇔ BufferedOutputStream ⇔ • •

BufferedReader BufferedWriter

Buffer of bytes (chars) to InputStream / Output Stream in order to speed processing up! Explicit specification of buffer size is possible.

From its Javadoc description • • • •

“A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods. When the BufferedInputStream is created, an internal buffer array is created. As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time. The mark operation remembers a point in the input stream and the reset operation causes all the bytes read since the most recent mark operation to be reread before new bytes are taken from the contained input stream. “

14 Concatenating two Streams SequenceInputStream •

Seamlessly glue together two or more input streams to create a long stream.

f3 = new SequenceInputStream(f1,f2);

15 DataInputStream / Data OutputStream •

Implements DataInput / DataOutput (RandomAccessFile)



Complete data compatibility btw the two!

8

EE 497 Java Programming



Implementing these interfaces require that implementing classes should handle EOF differently via exception handling as opposed to returning simply -1.



Data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way.



An application uses a data output stream to write data that can later be read by a data input stream.



Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8.

16 PrintStream & PrintWriter



Similar to DataOutputStream - Except println is supported. System.out.println("Hello") out - Static PrintStream variable in class System.



print - Immediate writing of data is not forced.

17 ObjectOutputStream/ ObjectInputStream •

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.



The objects can be read (reconstituted) using an ObjectInputStream. An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.



Persistent storage of objects can be accomplished by using a file for the stream.



If the stream is a network socket stream, the objects can be reconsituted on another host or in another process.



Only objects that support the java.io.Serializable interface can be written to streams.



The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects.



The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream.



The method readObject is used to read an object from the stream. Java's safe casting should be used to get the desired type.

9

EE 497 Java Programming



The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.



For example to write an object that can be read: FileOutputStream ostream = new FileOutputStream("t.tmp"); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeInt(12345); p.writeObject("Today"); p.writeObject(new Date()); p.flush(); ostream.close();



For example to read from a stream as written by the example in ObjectOutputStream: FileInputStream istream = new FileInputStream("t.tmp"); ObjectInputStream p = new ObjectInputStream(istream); int i = p.readInt(); String today = (String)p.readObject(); Date date = (Date)p.readObject(); istream.close();



Serialization: What is read or written is not a byte or an array of bytes, but an object!

18 Java’s File Management Methods •

Class File •

To name files



To query file attributes



To manipulate directories

19 Reading Files 1. RandomAccessFile class methods 2. Use streams 20 RandomAccessFile •

Class RandomAccessFile •

DataOutput methods



DataInput methods



4 other methods

10

EE 497 Java Programming

• • • • •

DataOutput - DataInput: Pretty symmetrical except minor differences •



21

seek() - Random-access reading and writing capability getFilePointer() - Where the next read or write will occur. For a newly opened file, it points length() close()

skipBytes(), readLine(), writeByte()/chars

No open() method!

Tokenizing Input Streams



Tokens: Recurring chunks of data in the stream.



Tokenizing: Reducing an input stream into a simpler stream of tokens.



Three types of tokens.

Syntax Table Defined 1. Words - Multicharacter tokens.

Specify which ASCII characters should be treated as one of them!

2. Single character tokens 3. Whitespace •

Class StreamTokenizer •

nextToken() method: Its return value tells what type of token •

TT_WORD=-3



TT_EOF=-1



TT_EOL='\n' invoked.



TT_NUMBER=-2

multicharacter or single character token nval or sval variables the end of the stream end of line if eolIsSignificant(true) has been

number

11