Io Stream Oops Unit III-part II
Io Stream Oops Unit III-part II
Java performs I/O through Streams. A Stream is linked to a physical device by java I/O system
to make input and output operation in java. The physical device can be disk file,
a keyboard, or a network socketIn general, a stream means continuous flow of data. Streams are
clean way to deal with input/output .Java implements streams within class hierarchies defined in
the java.io package.
Java defines two types of streams: byte and character. Byte streams provide a convenient
means for handling input and output of bytes. Byte streams are used, for example, when reading
or writing binary data. Character streams provide a convenient means for handling input and
output of characters. They use Unicode and, therefore, can be internationalized.
The byte stream classes provide a rich environment for handling byte-oriented I/O. A byte
stream can be used with any type of object, including binary data. This versatility makes
byte streams important to many types of programs.Byte streams process data byte by byte (8
bits). Byte stream is defined by using two abstract class at the top of hierarchy, they
areInputStream and OutputStream.
These two abstract classes have several concrete classes that handle various devices such
as disk files, network connection etc. Some important byte stream classes are shown in the
following table.
1.1 InputStream
InputStreamis an abstract class that defines Java’s model of streaming byte input.. Most of the
methods in this class will throw an IOExceptiononerrorConditions.InputStream facilitate
various methods. Most important ones are listed below
1.2 OutputStream
OutputStreamis an abstract class that defines streaming byte output. Most of the methods in
this class return void and throw an IOExceptionin the case of errors. Most important methods of
OutputStream are listed below.
1.3 FileInputStream
The FileInputStreamclass creates an InputStreamthat you can use to read bytes from a file.Its
two most common constructors are shown here:
FileInputStream(String filepath)
FileInputStream(File fileObj)
Either can throw a FileNotFoundException. Here, filepathis the full path name of a file, and
fileObjis 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:
1.4 FileOutputStream
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, booleanappend)
FileOutputStream(File fileObj, booleanappend)
They can throw a FileNotFoundException. Here, filePathis the full path name of a file, and
fileObjis a File object that describes the file. If append is true, the file is opened in append
mode. Creation of a FileOutputStreamis not dependent on the file already existing.
FileOutputStreamwill 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 IOExceptionwill be
thrown.
BufferedInputStreamir=new BufferedInputStream(System.in);
myOut.close();
myIn.close();
}
}
For the byte-oriented streams, a buffered stream extends a filtered stream class by attaching
a memory buffer to the I/O streams. This buffer allows Java to do I/O operations on more
than a byte at a time, hence increasing performance. The buffered byte stream classes are
BufferedInputStreamandBufferedOutputStream.
BufferedInputStream
BufferedInputStream(InputStreaminputStream)
BufferedInputStream(InputStreaminputStream, intbufSize)
The first form creates a buffered stream using a default buffer size. In the second, the size
of the buffer is passed in bufSize. The most important method of BufferedInputStream is “read”.
BufferedOutputStream
Buffers for output in Java are there to increase performance. Here are the two available
constructors:
BufferedOutputStream(OutputStreamoutputStream)
BufferedOutputStream(OutputStreamoutputStream, intbufSize)
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.
//Demonstration of BufferedInputStream
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
BufferedInputStreamir=new BufferedInputStream(System.in);
myOut.close();
myIn.close();
}
}
1.6 PrintStream
The PrintStreamclass provides all of the output capabilities we have been using from
the System file handle, System.out. This makes PrintStreamone of Java’s most often
used classes.
PrintStreamdefines several constructors. The ones shown next have been specified
from the start:
PrintStream(OutputStreamoutputStream)
PrintStream(OutputStreamoutputStream, booleanflushOnNewline)
PrintStream(OutputStreamoutputStream, booleanflushOnNewline,
String charSet)
The next set of constructors give you an easy way to construct a PrintStreamthat writes
its output to a file.
1.7Serialization
Serialization is the process of writing the state of an object to a byte stream. This is useful when
you want to save the state of your program to a persistent storage area, such as a file.At a later
time, you may restore these objects by using the process of deserialization. The byte stream
created is platform independent. So, the object serialized on one platform can be deserialized on
a different platform.
Serialization is also needed to implement Remote Method Invocation (RMI). RMI allows a Java
object on one machine to invoke a method of a Java object on a different machine. An object
may be supplied as an argument to that remote method. The sending machine seralizes the object
and transmits it. The receiving machine deserializes it.
Example: ATM: When the account holder tries to withdraw money from the server through
ATM, the account holder information like withdrawl details will be serialized and sent to server
where the details are deserialized and used to perform operations.
Advantages of Serialization
1. To save/persist state of an object into a file or database. Following figure shows the way to
save the state of an object into a file or database.
2. To travel an object across a network. Following figure shows the way to travel an object
across a network
If a class is serializable, all of its subclasses are also serializable.Variables that are declared as
transient are not saved by the serialization facilities. Also, static variables are not saved.
ObjectOutputStream
The argument outStreamis the output stream to which serialized objects will be written.
Several commonly used methods of ObjectOutputinterface&ObjectOutputStream
are shown in the following Table . They will throw an IOExceptionon error conditions.
ObjectInputStream
The ObjectInputStreamclass extends the InputStreamclass and implements the ObjectInput
interface. ObjectInputStreamis responsible for reading objects from a stream. Aconstructor of
this class is
int id;
String name;
void read()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter an employee id and name");
id=sc.nextInt();
name=sc.next();
}
void display()
{
System.out.println(id + name);
}
}
public class SerializationDemo
{
public static void main(String[] args)throws IOException,ClassNotFoundException
{
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("Employee.txt"));
e.read();
//Serialization
out.writeObject(e);
out.close();
Note 1:All byte inputstream stream classes are the sub classes of
InputStream abstract class.
Note 2: All byte outputstream stream classes are the sub classes of
OutputStream abstract class.
The character stream classes support 16-bit Unicode characters, performing operations on
characters. The top of the character stream hierarchies are the Reader and Writer abstract
classes.
2.1 Reader
Reader is an abstract class that defines Java’s model of streaming character input. All of the
methods in this class will throw an IOExceptionon error conditions. Following table shows
popular methods in Reader.
2.2 Writer
Writer is an abstract class that defines streaming character output. All of the methods in this
class throw an IOExceptionin the case of errors. Following table shows popular methods of the
Writer.
2.3 FileReader
The FileReaderclass creates a Reader that you can use to read the contents of a file. Its two
most commonly used constructors are shown here:
FileReader(String filePath)
FileReader(File fileObj)
Either can throw a FileNotFoundException. Here, filePathis the full path name of a file, and
fileObjis a File object that describes the file.
2.4 FileWriter
FileWritercreates a Writer that you can use to write to a file. Its most commonly used
constructors are shown here:
FileWriter(String filePath)
FileWriter(String filePath, booleanappend)
FileWriter(File fileObj)
FileWriter(File fileObj, booleanappend)
They can throw an IOException. Here, filePathis the full path name of a file, and fileObjis a File
object that describes the file. If append is true, then output is appended to the end of the file.
//Demonstration of FileReader and FileWriter .Filewriteread demonstration using character I/O
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
public class FileWriteReadDemo
{
public static void main(String[] args) throws IOException
{
FileWritermyOut = new FileWriter("input.txt");
BufferedReaderir=new BufferedReader(new InputStreamReader(System.in));
System.out.println("FILE WRITING: Enter text to be place into the file");
char ch=(char)ir.read();// reading of character from keyboard
while((c=br.read())!=-1)
System.out.print((char)c);
myIn.close();
}
}
2.5 BufferedReader
BufferedReader(Reader inputStream)
BufferedReader(Reader inputStream, intbufSize)
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.
2.6 BufferedWriter
BufferedWriter(Writer outputStream)
BufferedWriter(Writer outputStream, intbufSize)
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.
}
2.7 PrintWriter
PrintWriter(OutputStreamoutputStream)
PrintWriter(OutputStreamoutputStream, booleanflushOnNewline)
PrintWriter(Writer outputStream)
PrintWriter(Writer outputStream, booleanflushOnNewline)
parameter controls whether the output buffer is automatically flushed every time println( ),is
called. If flushOnNewlineistrue, flushing automatically takes place. If false, flushing is not
automatic. Constructors that do not specify the flushOnNewlineparameterdo not automatically
flush.
The next set of constructors give you an easy way to construct a PrintWriterthat writes its
output to a file.
StringReader Class:
Java StringReader class is a character stream with string as a source. It takes an input string and
changes it into character stream. It inherits Reader class.
In StringReader class, system resources like network sockets and files are not used, therefore
closing the StringReader is not necessary.
import java.io.StringReader;
public class StringReaderExample {
public static void main(String[] args) throws Exception {
String srg = "Hello Java!! \nWelcome to Javatpoint.";
StringReader reader = new StringReader(srg);
int k=0;
while((k=reader.read())!=-1){
System.out.print((char)k);
}
}
}
StringWriter class:
public class StringWriterextendsWriter
A character stream that collects its output in a string buffer, which can then be used to construct
a string.
Closing a StringWriter has no effect. The methods in this class can be called after the stream has
been closed without generating an IOException.
Note 1:All character input streams classes are the sub classes of Reader
abstract class.
Note 2: All character outputs stream classes are the sub classes of Writer
abstract class.
3. File class
Java File class represents the files and directory pathnames in an abstract manner. This class is
used for creation of files and directories, file searching, file deletion, etc.
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
Here, directoryPath is the path name of the file, filename is the name of the file, and dirObj is
a File object that specifies a directory.
// Demonstrate File.
import java.io.File;
class FileCreate
{
public static void main(String[] args)
{
File file = new File("HelloJavaExample.java");
System.out.println("File Exists : "+file.exists());
System.out.println("Length of File is : "+file.length());
System.out.println("Can Read File : "+file.canRead());
System.out.println("Can Write to File : "+file.canWrite());
System.out.println("whether File is a Directory : "+file.isDirectory());
System.out.println("whether File is a File : "+file.isFile());
System.out.println("File name is : "+file.getName());
System.out.println("File absolute path is : "+file.getAbsolutePath());
System.out.println("File path is : "+file.getPath());
System.out.println("File parent directory is : "+file.getParent());
System.out.println("File last modified on : "+ new java.util.Date(file.lastModified()));
}
}
NOTE: REFER RECORD FOR THE REMINING PROGRAMS