Monday 26 November 2012

Java Programming -- Streams in Java

Java Programming -- Streams in Java
Structure
6.1 Introduction to Streams
Objectives
Self Assessment Questions
6.2 The Abstract Streams
Self Assessment Questions
6.3 Stream Classes
Self Assessment Questions
6.4 Readers and Writers
Self Assessment Questions
6.5 Random Access Files
6.6 Serialization
6.7 Summary
6.8 Terminal Questions
6.1 Introduction to Streams
All programs accept input from a user, process it and produce an output. Therefore, all programming languages support input and output operations. Java provides support for input and output through the classes of the java.io package.
Java handles all input and output in the form of streams. A stream is a sequence of bytes traveling from a source to a destination over a communication path. If a program writes o a steam, it is the stream’s source. Similarly, if it is reading from a stream, it is the stream’s destination. Streams are powerful because they abstract the details of input/output (I/O) operations.
Java Programming Unit 6
Sikkim Manipal University Page No. 132
The two basic streams used are the input and the output streams. Each stream has a particular functionality. You can only read from an input stream and conversely, you can only write to an output stream.
Some streams are classified as node stream because they read from or write to a specific place like a disk file or memory. Some streams are classified as filters. Filters are used to read data from one stream and write it to another stream.
The two major classes for byte streams are InputStream and OutputStream. These abstract classes are subclassed to provide a variety of I/O capabilities. The InputStream class lays the foundation for the input class hierarchy, whereas the OutputStream class lays the foundation for the output class hierarchy.
The diagrams given below represent the hierarchy of the two streams.
InputStream Class Hierarchy
Java Programming Unit 6
Sikkim Manipal University Page No. 133
OutputStream Class Hierarchy
JDK 1.1 introduces the Reader and the Writer classes for Unicode I/O. These classes support internationalization. The hierarchy of these classes is given below.
Reader Class Hierarchy
Java Programming Unit 6
Sikkim Manipal University Page No. 134
Writer Class Hierarchy
Objectives
In this chapter, you will learn about the:
 Introduction to Streams
 Abstract Streams
 Stream Classes
 Implementing Streams.
Self Assessment Questions
1. What do you mean by streams?
Java Programming Unit 6
Sikkim Manipal University Page No. 135
6.2 The Abstract Streams
Methods of the InputStream Class Method Explanation
int read ()
Reads a byte of data from the input stream
int read (byte [] b)
Reads bytes of data from the input stream and stores them in the array
int read (byte [] b, int off, int len)
Reads the number of bytes specified by the third argument from the input stream and stores it in the array. The second argument specifies the position from where the bytes have to be read.
int available ()
Returns the number of bytes available for reading from the input stream
void close ()
Close an input stream and releases all the resources associated with it.
Markable Streams
Markable streams provide the capability of placing “bookmarks” on the stream and resetting it. This stream can then be read from the marked position. If a stream is marked, it must have some memory associated with it to keep track of the data between the mark and the current position of the stream. Method Explanation
boolean markSupported ()
Returns true if the stream supports a bookmark
void mark (int readlimit )
Marks a position on the stream and identifies the number of bytes that can be read before the mark becomes invalid.
void reset ()
Repositions the stream to its last marked position.
long skip (long n)
Skips a specific number of bytes in the stream.
Java Programming Unit 6
Sikkim Manipal University Page No. 136
Methods of the OutputStream Class Method Explanation
void write (int n)
Writes the specified byte of data to the output stream.
void write (byte [] b )
Writes an array of bytes to the output stream.
void write (byte [] b, int off, int len )
Writes a segment of an array to the output streams.
void flush ()
Force writes whenever the data accumulates in the output stream.
void close ()
Cause the output stream to close. Any data present on it is stored before the stream is deallocated from the memory.
Self Assessment Questions
1. What are the different methods used in InputStream class?
2. What are the different methods used in OutputStream class?
6.3 Stream Classes
The FileInputStream and FileOutputStream Classes
These streams are classified as mode streams as they read and write data from disk files. The classes associated with these streams have constructors that allows you to specify the path of the file to which they are connected. The FileInputStream class allows you to read input from a file in the form of a stream. The FileOutputStream class allows you to write output to a file stream.
Example
FileInputStream inputfile = new FileInputStream (“Employee.dat”);
FileOutputStream outputfile = new FileOutputStream (“binus.dat”);
The BufferedInputStream and BufferedOutputStream Classes
The BufferedInputStream class creates and maintains a buffer for an input stream. This class is used to increase the efficiency of input operations. This
Java Programming Unit 6
Sikkim Manipal University Page No. 137
is done by reading data from the stream one byte at a time. The BufferedOutputStream class creates and maintains a buffer for the output stream. Both the classes represents filter streams.
The DataInputStream and DataOutputStream Classes
The DataInputStream and DataOutputStream classes are filter streams that allow the reading and writing of Java primitive data types.
The DataInputStream class provides the capability to read primitive data types from an input stream. It implements the methods presents in the DataInput interface.
Methods of the DataInputStream class Method Explanation
boolean readBoolean ()
Reads one byte and returns true if that byte is nonzero, false if it is zero.
byte readByte ()
Reads a byte as an 8-bit signed value.
char readChar ()
Reads a Unicode character.
int readInt ()
Reads an integer value.
The DataInputStream class provides methods that are complementary to the methods of DataInputStream classes. It keeps track of the number of bytes written to the output stream.
Methods of the DataOutputStream Class Method Explanation
void writeChar (int v )
Writes a character to the output stream.
void writeLong (long v)
Writes a long integer to the output stream.
void writeInt (int v )
Writes an integer to the output stream.
Java Programming Unit 6
Sikkim Manipal University Page No. 138
The ByteArrayInputStream and ByteArrayOutputStream Classes
These classes allow you to read and write to an array of bytes. Method Explanation
ByteArrayInputStream (byte [] b)
Creates an input stream of the array of byes
int size ()
Returns the total number of bytes written to the stream.
Self Assessment Questions
1. What are the uses of FileInputStream and FileOutputStream?
2. What are the uses of BufferedInputStream and BufferedOutputStream?
6.4 Readers and Writers
Introduction to Readers and Writers
The subclasses of the input and output streams read and write data in the form of bytes. The Reader and Writer classes are abstract classes that support the reading and writing of Unicode character streams. Unicode is used to represents data such that each character is represented by 16 bits. Byte streams work on eight bits of data. These 16-bit version streams are called reader and writer.
The most important subclasses of the Reader and Writer classes are InputStreamReader and OutputStreamWriter. These classes are used as interfaces between byte streams and character readers and writers.
The Reader class supports InputStream class methods like read(), skip(), mark(), markSupported(), reset() and close().
The writer class supports methods of the OutputStream class like write(), flush() and close().
Reading from the Keyboard
The InputStreamReader and OutputStreamReader classes are used to convert data between the byte and Unicode character streams. The
Java Programming Unit 6
Sikkim Manipal University Page No. 139
InputStreamReader class converts an InputStream subclass object into Unicode character stream. The OutputStreamWriter class converts a Unicode character output stream into a byte output stream.
Buffered character I/O is supported by the BufferedReader and BufferedWriter classes. The readLine() method of the BufferedReader class is used for reading lines of text from the console, the file, or other input streams.
In the above code, the InputStreamReader constructor takes an object of the InputStream class System.in as its parameter and constructs an InoutStreamReader object called inputReader. Passing the InputStreamReader object as a parameter to the constructor of BufferedReader creates a BufferedReader object. The readLine () method of BufferedReader reads the line from the console. This line is then
Java Programming Unit 6
Sikkim Manipal University Page No. 140
displayed as a message in the screen. You have to press Enter to terminate the program.
Self Assessment Questions
1. What is the use of a Reader and a Writer class?
6.5 Random Access Files
The term random access means that data can be read from or written to random locations within a file. In all the above mentioned streams, data is read and written as a continuous stream of information. Java provides the RandomAccessFile class to perform I/O operations a t specified locations within a file.
The RandomAccessFile class implements the DataInput and DataOutput interfaces for performing I/O using the primitive data types. The RandomAccessFile class also supports permissions like read and write, and allows files to be accessed in read-only and read-write modes.
Creating a Random Access File
There are two ways to create a random access file- using the pathname as a string or using an object of the File class.
RandomAccessFile (String pathname, String mode);
RandomAccessFile (File name, String mode);
Example
randomFile = new RandomAccessFile (“iotets.txt”,”rw”);
or
File file1 = new File (“iotest.txt”);
RandomAccessFile randomFile = new RandomAccessFile (file1, “rw”);
Java Programming Unit 6
Sikkim Manipal University Page No. 141
The second argument is the mode argument that determines whether you have read-only or read/write (rw) access to the file.
The RandomAccessFile class has several methods that allow random access to the content within the file. Method Explanation
void seek (long pos )
Sets the file pointer to a particular location inside the file.
long getFilePointer ()
Return the current location of the file pointer.
long length ()
Returns the length of the file, in bytes.
6.6 Serialization
When you create a file using a text editor, it allows you to store the text to a file. The text stored in the file is the data encapsulated within the file object. This object is permanently available once you store it on the disk. The capability of an object to exist beyond the execution of the program that created it is know as persistence.
In the above example, the file object continues to exist even after the text editor stops executing. To make the file object persistent, you have to carry out an important step: saving the file. Saving the file object is called serialization. Serialization is the key to implementing persistence. It provides the capability for you to write an object to a stream and read the object at a later stage.
JDK 1.2 provides the Serializable interface in the java.io package to support object serialization. The process of reading an object and writing it to a file stream is very simple. The readObject () method of the ObjectInputStream class is used to read objects from the stream.
The Objects that are read should be cast to the appropriate class names. Similarly, the writeObject () method of the ObjectOutputStream class writes objects to a stream.
Java Programming Unit 6
Sikkim Manipal University Page No. 142
6.7 Summary
 The classes of the java.io package provide support for input and output operations in Java programs.
 A stream is a sequence of bytes traveling from a source to a destination over a communication path.
 InputStream and OutputStream are superclasses used for reading from and writing to byte streams.
 The Reader and Writer classes support I/O for Unicode character.
 The RandomAccessFile class supports random access operations in files.
6.8 Terminal Questions
1. What are the uses of a stream class?
2. What is the syntax of FileInputStream and FileOutputStream ?
3. What are the different methods under BufferedInputStream and BufferedOutputStream?
4. What are the uses of random access file over sequential access file?

No comments:

Post a Comment