JAVA UNIT4 - M.Bommy PDF
JAVA UNIT4 - M.Bommy PDF
void close( ) Closes the output stream. Further write attempts will generate an
IOException.
void flush( ) Finalizes the output state so that any buffers are cleared. That is, it
flushes the output
void write(int b) Writes a single byte to an output stream. Note that the parameter is
an int, which allows you to call write( ) with an expression without
having to cast it back to byte.
void write(byte buffer[ ]) Writes a complete array of bytes to an output stream.
void write(byte buffer[ ], int offset, int Writes a subrange of numBytes bytes from the array buffer, beginning at
numBytes) buffer[offset].
FileInputStream
The FileInputStream class creates an InputStream that you can use to read bytes from a file.
Two commonly used constructors are shown here:
• FileInputStream(String filePath)
• FileInputStream(File fileObj)
Either can throw a FileNotFoundException.
Here, filePath is the full path name of a file, and fileObj is a File object that describes the file.
The following example creates two FileInputStreams that use the same disk file and each of
the two constructors:
o FileInputStream f0 = new FileInputStream("/autoexec.bat")
o File f = new File("/autoexec.bat");
o FileInputStream f1 = new FileInputStream(f);
FileInputStream overrides six of the methods in the abstract class InputStream. The
mark( ) and reset( ) methods are not overridden, and any attempt to use reset( ) on
a FileInputStream will generate an IOException.
FileOutputStream
FileOutputStream creates an OutputStream that you can use to write bytes to a
file. It implements the AutoCloseable, Closeable, and Flushable interfaces.
Four of its constructors are shown here:
o FileOutputStream(String filePath)
o FileOutputStream(File fileObj)
o FileOutputStream(String filePath, boolean append)
o FileOutputStream(File fileObj, boolean append)
They can throw a FileNotFoundException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file. If append is true, the file is opened in
append mode.
ByteArrayInputStream
ByteArrayInputStream is an implementation of an input stream that uses a byte
array as the source. This class has two constructors, each of which requires a byte
array to provide the data source:
• ByteArrayInputStream(byte array [ ])
• ByteArrayInputStream(byte array [ ], int start, int numBytes)
Here, array is the input source.The second constructor creates an InputStream from a subset
of the byte array that begins with the character at the index specified by start and is
numBytes long.
The close( ) method has no effect on a ByteArrayInputStream.
Therefore, it is not necessary to call close( ) on a ByteArrayInputStream, but doing
so is not an error.
A ByteArrayInputStream implements both mark( ) and reset( ).
ByteArrayOutputStream
ByteArrayOutputStream is an implementation of an output stream that uses a byte array
as the destination.
ByteArrayOutputStream has two constructors, shown here:
o ByteArrayOutputStream( )
o ByteArrayOutputStream(int numBytes)
In the first form, a buffer of 32 bytes is created. In the second, a buffer is created with a
size equal to that specified by numBytes. The buffer is held in the protected buf field of
ByteArrayOutputStream.The buffer size will be increased automatically, if needed.
The number of bytes held by the buffer is contained in the protected count field of
ByteArrayOutputStream.
The close( ) method has no effect on a ByteArrayOutputStream. Therefore, it is not
necessary to call close( ) on a ByteArrayOutputStream, but doing so is not an error.
Filtered Byte Streams
Filtered streams are simply wrappers around underlying input or output streams that transparently
provide some extended level of functionality. These streams sit on top of an already
existing output stream (the underlying output stream) which it uses as its basic sink of data,
but possibly transforming the data along the way or providing additional functionality.
These streams are typically accessed by methods that are expecting a generic stream,
which is a superclass of the filtered streams.
Typical extensions are buffering, character translation, and raw data translation.
The filtered byte streams are FilterInputStream and FilterOutputStream.
Their constructors are shown here:
o FilterOutputStream(OutputStream os)
o FilterInputStream(InputStream is)
The methods provided in these classes are identical to those in InputStream and
OutputStream.
Buffered Byte Streams
For the byte-oriented streams, a buffered stream extends a filtered stream class by
attaching a memory buffer to the I/O stream.
This buffer allows Java to do I/O operations on more than a byte at a time, thereby
improving performance.
Because the buffer is available, skipping, marking, and resetting of the stream
become possible.
The buffered byte stream classes are BufferedInputStream and
BufferedOutputStream.
BufferedInputStream
Buffering I/O is a very common performance optimization. Java’s BufferedInputStream
class allows you to "wrap" any InputStream into a buffered stream to improve
performance.
BufferedInputStream has two constructors:
o BufferedInputStream(InputStream inputStream)
o BufferedInputStream(InputStream inputStream, int bufSize)
The first form creates a buffered stream using a default buffer size. In the second, the size
of the buffer is passed in bufSize.
BufferedInputStream also supports the mark( ) and reset( ) methods.
This support is reflected by BufferedInputStream.markSupported( ) returning true.
BufferedOutputStream
Unlike buffered input, buffering output does not provide additional
functionality.
Buffers for output in Java are there to increase performance. Here are the
two available constructors:
o BufferedOutputStream(OutputStream outputStream)
o BufferedOutputStream(OutputStream outputStream, int bufSize)
The first form creates a buffered stream using the default buffer size. In the
second form, the size of the buffer is passed in bufSize.
PushbackInputStream
One of the novel uses of buffering is the implementation of pushback. Pushback is used on
an input stream to allow a byte to be read and then returned (that is, "pushed back") to
the stream. The PushbackInputStream class implements this idea. It provides a mechanism
to "peek" at what is coming from an input stream without disrupting it.
PushbackInputStream has the following constructors:
PushbackInputStream(InputStream inputStream)
PushbackInputStream(InputStream inputStream, int numBytes)
The first form creates a stream object that allows one byte to be returned to the input
stream.
The second form creates a stream that has a pushback buffer that is numBytes long. This
allows multiple bytes to be returned to the input stream.
Beyond the familiar methods of InputStream, PushbackInputStream provides unread( ),
shown here:
o void unread(int b)
o void unread(byte buffer [ ])
o void unread(byte buffer, int offset, int numBytes)
The first form pushes back the low-order byte of b. This will be the next byte returned by
a subsequent call to read( ). The second form pushes back the bytes in buffer. The third
form pushes back numBytes bytes beginning at offset from buffer.
An IOException will be thrown if there is an attempt to push back a byte when the
pushback buffer is full.
SequenceInputStream
The SequenceInputStream class allows you to concatenate multiple InputStreams, ie reads
data from multiple streams. The construction of a SequenceInputStream is different from
any other InputStream.
A SequenceInputStream constructor uses either a pair of InputStreams or an Enumeration
of InputStreams as its argument:
SequenceInputStream(InputStream first, InputStream second)
SequenceInputStream(Enumeration <? extends InputStream> streamEnum)
Operationally, the class fulfills read requests from the first InputStream until it runs out
and then switches over to the second one. In the case of an Enumeration, it will continue
through all of the InputStreams until the end of the last one is reached. When the end of
each file is reached, its associated stream is closed. Closing the stream created by
SequenceInputStream causes all unclosed streams to be closed.
PrintStream
The PrintStream class provides all of the output capabilities we have been using from the System
file handle, System.out. This makes PrintStream one of Java’s most often used classes. It
implements the Appendable,AutoCloseable, Closeable, and Flushable interfaces.
PrintStream defines several constructors.The one of them is:
PrintStream(OutputStream outputStream)
PrintStream(OutputStream outputStream, boolean autoFlushingOn)
PrintStream(OutputStream outputStream, boolean autoFlushingOn String charSet)
throws UnsupportedEncodingException
Here, outputStream specifies an open OutputStream that will receive output. The autoFlushingOn
parameter controls whether the output buffer is automatically flushed every time a newline (\n)
character or a byte array is written or when println( ) is called. If autoFlushingOn is true, flushing
automatically takes place. If it is false, flushing is not automatic. The first constructor does not
automatically flush.You can specify a character encoding by passing its name in charSet.
The next set of constructors gives you an easy way to construct a PrintStream that writes its
output to a file:
PrintStream(File outputFile) throws FileNotFoundException
PrintStream(File outputFile, String charSet) throws FileNotFoundException,
UnsupportedEncodingException
PrintStream(String outputFileName) throws FileNotFoundException
PrintStream(String outputFileName, String charSet) throws FileNotFoundException,
UnsupportedEncodingException
These allow a PrintStream to be created from a File object or by specifying the name of a file. In
either case, the file is automatically created. Any preexisting file by the same name is destroyed.
Once created, the PrintStream object directs all output to the specified file. You can specify a
character encoding by passing its name in charSet.
PrintStream supports the print( ) and println( ) methods for all types, including
Object.
If an argument is not a primitive type, the PrintStream methods will call the
object’s toString( ) method and then display the result.
Somewhat recently (with the release of JDK 5), the printf( ) method was added to
PrintStream. It allows you to specify the precise format of the data to be written.
The printf( ) method uses the Formatter class to format data. It then writes this
data to the invoking stream.
DataOutputStream and DataInputStream
DataOutputStream and DataInputStream enable you to write or read primitive
data to or from a stream.
They implement the DataOutput and DataInput interfaces, respectively.
These interfaces define methods that convert primitive values to or from a
sequence of bytes.
These streams make it easy to store binary data, such as integers or floating-point
values, in a file.
DataOutputStream
DataOutputStream extends FilterOutputStream, which extends OutputStream. In
addition to implementing DataOutput, DataOutputStream also implements
AutoCloseable, Closeable, and Flushable.
DataOutputStream defines the following constructor:
DataOutputStream(OutputStream outputStream)
Here, outputStream specifies the output stream to which data will be written.
When a DataOutputStream is closed (by calling close( )), the underlying stream
specified by outputStream is also closed automatically.
DataOutputStream supports all of the methods defined by its superclasses.
However, it is the methods defined by the DataOutput interface, which it
implements, that make it interesting.
DataOutput defines methods that convert values of a primitive type into a byte
sequence and then writes it to the underlying stream. Here is a sampling of these
methods:
final void writeDouble(double value) throws IOException
final void writeBoolean(boolean value) throws IOException
final void writeInt(int value) throws IOException
Here, value is the value written to the stream.
DataInputStream
DataInputStream is the complement of DataOuputStream. It extends
FilterInputStream, which extends InputStream. In addition to implementing the
DataInput interface, DataInputStream also implements AutoCloseable and
Closeable.
Here is its only constructor:
DataInputStream(InputStream inputStream)
Here, inputStream specifies the input stream from which data will be read. When a
DataInputStream is closed (by calling close( )), the underlying stream specified by
inputStream is also closed automatically.
DataInputStream supports all of the methods of its superclasses, but it is the
methods defined by the DataInput interface that make it unique. These methods
read a sequence of bytes and convert them into values of a primitive type.
Here is a sampling of these methods:
final double readDouble( ) throws IOException
final boolean readBoolean( ) throws IOException
final int readInt( ) throws IOException
THECHARACTER STREAM CLASSES
While the byte stream classes provide sufficient functionality to handle any type of I/O
operation, they cannot work directly with Unicode characters. The java.io package
provides CharacterStream classes to overcome the limitations of ByteStream classes,
which can only handle the 8-bit bytes and is not compatible to work directly with the
Unicode characters. Since one of the main purposes of Java is to support the "write once,
run anywhere" philosophy, it was necessary to include direct I/O support for characters.
CharacterStream classes are used to work with 16-bit Unicode characters. They can
perform operations on characters, char arrays and Strings.
However, the CharacterStream classes are mainly used to read characters from the source
and write them to the destination. For this purpose, the CharacterStream classes are
divided into two types of classes, I.e., Reader class andWriter class.
At the top of the character stream hierarchies are the Reader and Writer abstract
classes.
Reader
Reader is an abstract class that defines Java’s model of streaming character input.
It implements the AutoCloseable, Closeable, and Readable interfaces. All of the
methods in this class (except for markSupported( )) will throw an IOException on
error conditions.
Following table provides a synopsis of the methods in Reader.
Writer
Writer is an abstract class that defines streaming character output.
It implements the AutoCloseable, Closeable, Flushable, and Appendable interfaces.
All of the methods in this class throw an IOException in the case of errors.
The following table shows a synopsis of the methods in Writer.
FileReader
The FileReader class creates a Reader that you can use to read the contents of a
file.
Two commonly used constructors are shown here:
FileReader(String filePath)
FileReader(File fileObj)
Either can throw a FileNotFoundException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file.
FileWriter
FileWriter creates a Writer that you can use to write to a file.
Four commonly used constructors are shown here:
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
They can all throw an IOException. Here, filePath is the full path name of a file, and fileObj is
a File object that describes the file. If append is true, then output is appended to the end of the
file.
Creation of a FileWriter is not dependent on the file already existing. FileWriter will
create the file before opening it for output when you create the object. In the case where
you attempt to open a read-only file, an IOException will be thrown.
CharArrayReader
CharArrayReader is an implementation of an input stream that uses a character
array as the source.
This class has two constructors, each of which requires a character array to provide
the data source:
CharArrayReader(char array [ ])
CharArrayReader(char array [ ], int start, int numChars)
Here, array is the input source. The second constructor creates a Reader from a subset of your
character array that begins with the character at the index specified by start and is
numChars long.
The close( ) method implemented by CharArrayReader does not throw any
exceptions.
CharArrayWriter
CharArrayWriter is an implementation of an output stream that uses an array as
the destination.
CharArrayWriter has two constructors, shown here:
o CharArrayWriter( )
o CharArrayWriter(int numChars)
In the first form, a buffer with a default size is created. In the second, a buffer is
created with a size equal to that specified by numChars. The buffer is held in the buf
field of CharArrayWriter. The buffer size will be increased automatically, if needed.
The number of characters held by the buffer is contained in the count field of
CharArrayWriter. Both buf and count are protected fields.
The close( ) method has no effect on a CharArrayWriter.
BufferedReader
BufferedReader improves performance by buffering input.
It has two constructors:
o BufferedReader(Reader inputStream)
o BufferedReader(Reader inputStream, int bufSize)
The first form creates a buffered character stream using a default buffer size. In the
second, the size of the buffer is passed in bufSize.
BufferedWriter
A BufferedWriter is a Writer that buffers output. Using a BufferedWriter can
improve performance by reducing the number of times data is actually physically
written to the output device.
A BufferedWriter has these two constructors:
BufferedWriter(Writer outputStream)
BufferedWriter(Writer outputStream, int bufSize)
The first form creates a buffered stream using a buffer with a default size. In the
second, the size of the buffer is passed in bufSize.
PushbackReader
The PushbackReader class allows one or more characters to be returned to the input
stream. This allows you to look ahead in the input stream.
Here are its two constructors:
o PushbackReader(Reader inputStream)
o PushbackReader(Reader inputStream, int bufSize)
The first form creates a buffered stream that allows one character to be pushed back. In
the second, the size of the pushback buffer is passed in bufSize.
Closing a PushbackReader also closes the underlying stream specified by inputStream.
PushbackReader provides unread( ), which returns one or more characters to the
invoking input stream. It has the three forms shown here:
o void unread(int ch) throws IOException
o void unread(char buffer [ ]) throws IOException
o void unread(char buffer [ ], int offset, int numChars) throws IOException
PrintWriter
PrintWriter is essentially a character-oriented version of PrintStream. It implements the
Appendable,AutoCloseable, Closeable, and Flushable interfaces.
PrintWriter has several constructors. The following have been supplied by PrintWriter
from the start:
PrintWriter(OutputStream outputStream)
PrintWriter(OutputStream outputStream, boolean autoFlushingOn)
PrintWriter(Writer outputStream)
PrintWriter(Writer outputStream, boolean autoFlushingOn)
Here, outputStream specifies an open OutputStream that will receive output. The autoFlushingOn
parameter controls whether the output buffer is automatically flushed every time println( ),
printf( ), or format( ) is called. If autoFlushingOn is true, flushing automatically takes place.
If false, flushing is not automatic. Constructors that do no specify the autoFlushingOn
parameter do not automatically flush.
The next set of constructors gives you an easy way to construct a PrintWriter that writes
its output to a file.
PrintWriter(File outputFile) throws FileNotFoundException
PrintWriter(File outputFile, String charSet) throws FileNotFoundException,
UnsupportedEncodingException
PrintWriter(String outputFileName) throws FileNotFoundException
PrintWriter(String outputFileName, String charSet) throws FileNotFoundException,
UnsupportedEncodingException
These allow a PrintWriter to be created from a File object or by specifying the name of a
file. In either case, the file is automatically created.
PrintWriter also supports the printf( ) method.
The Collection Framework
The Collections Framework defines several core interfaces.
Hierarchy of the Collection Framework
The ArrayList Class
The ArrayList class extends AbstractList and implements the List interface.
ArrayList is a generic class that has this declaration:
• class ArrayList<E>
Here, E specifies the type of objects that the list will hold.
ArrayList supports dynamic arrays that can grow as needed.
In Java, standard arrays are of a fixed length. After arrays are created, they cannot
grow or shrink, which means that you must know in advance how many elements
an array will hold.
But, sometimes, you may not know until run time precisely how large an array
you need. To handle this situation, the Collections Framework defines ArrayList.
An ArrayList can dynamically increase or decrease in size.
Array lists are created with an initial size.
When this size is exceeded, the collection is automatically enlarged. When objects
are removed, the array can be shrunk
ArrayList has the constructors shown here:
• ArrayList( )
• ArrayList(Collection<? extends E> c)
• ArrayList(int capacity).
COLLECTION FRAMEWORK : LinkedList
The LinkedList class extends AbstractSequentialList and implements the List, Deque, and
Queue interfaces. It provides a linked-list data structure, which is a linear data structure
where the elements are not stored in contiguous locations.
LinkedList is a generic class that has this declaration:
class LinkedList<E>
Here, E specifies the type of objects that the list will hold.
LinkedList has the two constructors shown here:
• LinkedList( )
• LinkedList(Collection<? extends E> c)
The first constructor builds an empty linked list. The second constructor builds a linked
list that is initialized with the elements of the collection c.
Because LinkedList implements the Deque interface, you have access to the
methodsdefined by Deque.
For example, to add elements to the start of a list, you can use addFirst( ) or
offerFirst( ).
To add elements to the end of the list, use addLast( ) or offerLast( ).
To obtain the first element, you can use getFirst( ) or peekFirst( ). To obtain the
last element, use getLast( ) or peekLast( ).
To remove the first element, use removeFirst( ) or pollFirst( ).
To remove the last element, use removeLast( ) or pollLast( ).
COLLECTION FRAMEWORK: HashSet
HashSet extends AbstractSet and implements the Set interface. It creates a
collection that uses a hash table for storage.
HashSet is a generic class that has this declaration:
• class HashSet<E>
Here, E specifies the type of objects that the set will hold.
A hash table stores information by using a mechanism called hashing.
In hashing, the informational content of a key is used to determine a unique value,
called its hash code.
The hash code is then used as the index at which the data associated with the key is
stored.
The transformation of the key into its hash code is performed automatically.
The advantage of hashing is that it allows the execution time of add( ), contains( ),
remove( ), and size( ) to remain constant even for large sets.
The following constructors are defined:
HashSet( )
HashSet(Collection<? extends E> c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
It is important to note that HashSet does not guarantee the order of its elements,
because the process of hashing doesn’t usually lend itself to the creation of sorted
sets.
COLLECTION FRAMEWORK: LinkedHashSet
The LinkedHashSet class extends HashSet and adds no members of its own.
It is a generic class that has this declaration:
• class LinkedHashSet<E>
Here, E specifies the type of objects that the set will hold. Its constructors parallel those
in HashSet.
LinkedHashSet maintains a linked list of the entries in the set, in the order in which they
were inserted.
This allows insertion-order iteration over the set. That is, when cycling through a
LinkedHashSet using an iterator, the elements will be returned in the order in which they
were inserted.
COLLECTION FRAMEWORK: TreeSet
TreeSet extends AbstractSet and implements the NavigableSet interface. It
creates a collection that uses a tree for storage.
Objects are stored in sorted, ascending order.
Access and retrieval times are quite fast, which makes TreeSet an excellent
choice when storing large amounts of sorted information that must be found
quickly.
TreeSet is a generic class that has this declaration:
• class TreeSet<E>
Here, E specifies the type of objects that the set will hold.
TreeSet has the following constructors:
• TreeSet( )
• TreeSet(Collection<? extends E> c)
• TreeSet(Comparator<? super E> comp)
• TreeSet(SortedSet<E> ss)
ArrayList Vs Vector in Java
COLLECTION FRAMEWORK: Vector
Vector implements a dynamic array.
It is similar to ArrayList, but with two differences:
Vector is synchronized, and it contains many legacy methods that duplicate
the functionality of methods defined by the Collections Framework. With the
advent of collections, Vector was reengineered to extend AbstractList and to
implement the List interface.
Vector is declared like this:
class Vector<E>
Here, E specifies the type of element that will be stored.
Here are the Vector constructors:
• Vector( )
• Vector(int size)
• Vector(int size, int incr)
• Vector(Collection<? extends E> c)
COLLECTION FRAMEWORK: Stack
The stack is a linear data structure that is used to store the collection of objects. It
is based on Last-In-First-Out (LIFO). Provides different operations such as push,
pop, search, etc.
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Stack only defines the default constructor, which creates an empty stack.
Stack is declared as shown here:
• class Stack<E>
Here, E specifies the type of element stored in the stack.
Stack includes all the methods defined by Vector and adds several of its own, as
shown in the following table
In Java, Stack is a class that falls under the Collection
framework that extends the Vector class. It also
implements interfaces List, Collection, Iterable,
Cloneable, Serializable.
Collection Framework –Stack Class – PUSH Operation
import java.util.Stack; // pushing elements into stack
public class StackEmptyMethodExample stk.push(78);
{ stk.push(113);
public static void main(String[] args) stk.push(90);
{ stk.push(120);
//creating an instance of Stack class //prints elements of the stack
Stack<Integer> stk= new Stack<>(); System.out.println("Elements in Stack: " + st
// checking stack is empty or not k);
boolean result = stk.empty(); result = stk.empty();
System.out.println("Is the stack empty? " + r System.out.println("Is the stack empty? " + r
esult); esult);
}
}
OUTPUT??
Collection Framework –Stack Class – POP Operation
import java.util.Stack; // Remove element stacks
String element = animals.pop();
class Main { System.out.println("Removed
public static void main(String[] args) Element: " + element);
{ }
Stack<String> animals= new }
Stack<>(); OUTPUT:
Initial Stack: [Dog, Horse, Cat]
// Add elements to Stack Removed Element: Cat
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Initial Stack:
" + animals);
Collection Framework –Stack Class – peek() Method