0% found this document useful (0 votes)
7 views18 pages

Io Stream Oops Unit III-part II

The document discusses Java's I/O system, focusing on streams which facilitate input and output operations through the java.io package. It explains the two types of streams: byte streams for handling binary data and character streams for handling Unicode characters, detailing key classes such as InputStream, OutputStream, FileInputStream, FileOutputStream, and their buffered counterparts. Additionally, it covers serialization for object state persistence and provides examples of using various stream classes for file reading and writing.

Uploaded by

srinusirisala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views18 pages

Io Stream Oops Unit III-part II

The document discusses Java's I/O system, focusing on streams which facilitate input and output operations through the java.io package. It explains the two types of streams: byte streams for handling binary data and character streams for handling Unicode characters, detailing key classes such as InputStream, OutputStream, FileInputStream, FileOutputStream, and their buffered counterparts. Additionally, it covers serialization for object state persistence and provides examples of using various stream classes for file reading and writing.

Uploaded by

srinusirisala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

OOPS-IO STREAM IMPORTANT POINTS-UNIT 3 PART 2

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.

1.The Byte Stream

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:

FileInputStream f0 = new FileInputStream("/autoexec.bat")


File f = new File("/autoexec.bat");
FileInputStream f1 = new FileInputStream(f);

Important methods of FileInputStream

1.4 FileOutputStream

FileOutputStreamcreates an OutputStreamthat you can use to write bytes to a file. Its


most commonly used constructors are shown here:

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.

Important methods of FileOutputStream


//Demonstration of FileInpuStream and FileOutputStream.This program write/read the data from
file.
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

public class ByteWriteReadDemo


{

public static void main(String[] args) throws IOException


{

FileOutputStreammyOut = new FileOutputStream("bytefile.txt");

BufferedInputStreamir=new BufferedInputStream(System.in);

System.out.println("FILE WRITING: Enter text to be place into the file");


char ch;
do
{
// read next character from keyboard
ch=(char)ir.read();
//This loop gets interatedas long asch not equal to #

// place ch into the file


myOut.write(ch);
} while(ch!='0');

myOut.close();

//READING FROM FILE AND DISPLAY THE CONTENT ON THE MONITOR


FileInputStreammyIn = new FileInputStream("bytefile.txt");
BufferedInputStreambr=new BufferedInputStream(myIn);

System.out.println(" FILE READING: Contents of the file are");


int c;
while((c=br.read())!=-1)
System.out.print((char)c);

myIn.close();
}
}

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

Buffering I/O is a very common performance optimization. Java’s BufferedInputStreamclass


allows you to “wrap” any InputStreaminto a buffered stream and achieve this performance
improvement.

BufferedInputStreamhas two constructors:

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

ABufferedOutputStreamis similar to any OutputStreamwith the exception of an added


flush( )method that is used to ensure that data buffers are physically written to the actual
output device. Since the point of a BufferedOutputStreamis to improve performance by
reducing the number of times the system actually writes data, you may need to call flush( )
to cause any data that is in the buffer to be immediately written.

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;

public class ByteWriteReadDemo


{

public static void main(String[] args) throws IOException


{

FileOutputStreammyOut = new FileOutputStream("bytefile.txt");

BufferedInputStreamir=new BufferedInputStream(System.in);

System.out.println("FILE WRITING: Enter text to be place into the file");


char ch;
do
{
// read next character from keyboard
ch=(char)ir.read();
//This loop gets interatedas long asch not equal to #

// place ch into the file


myOut.write(ch);
} while(ch!='0');

myOut.close();

//READING FROM FILE AND DISPLAY THE CONTENT ON THE MONITOR


FileInputStreammyIn = new FileInputStream("bytefile.txt");
BufferedInputStreambr=new BufferedInputStream(myIn);

System.out.println(" FILE READING: Contents of the file are");


int c;
while((c=br.read())!=-1)
System.out.print((char)c);

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)

Here, outputStreamspecifies an open OutputStreamthat will receive output. The


flushOnNewlineparameter 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 flushOnNewlineistrue, flushing automatically takes place. If it is false, flushing is not


automatic. The firstconstructor does not automatically flush. You can specify a character
encoding by passingits name in charSet.

The next set of constructors give you an easy way to construct a PrintStreamthat 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

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

Only the objects of those classes which implementsjava.io.Serializable interface can be


serialized.

Serializable is a marker interface (has no data member and method). It means


Serializableinterface defines no members. It is simply used to indicate that a class may be
serialized.It is used to “mark” java classes so that objects of these classes may get certain
capability. Other examples of marker interfaces are:- Cloneable and Remote.

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.

Java Facilitates ObjectOutputStream and ObjectInputStream to save object


state(serialization) and recreate object(deserialization) respectively.

ObjectOutputStream

The ObjectOutputStreamclass extends the OutputStreamclass and implements the


ObjectOutputinterface. It is responsible for writing objects to a stream.
A constructor of
this class is

ObjectOutputStream(OutputStreamoutStream) throws IOException

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

ObjectInputStream(InputStreaminStream) throws IOException


The argument inStreamis the input stream from which serialized objects should be read.
Several commonly used methods of ObjectInputandObjectInputStream
are shown in the following Table . They will throw an IOExceptionon error conditions.
//Serialization Demo
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.Scanner;
import java.io.Serializable;

class Employee implements Serializable


{

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"));

Employee e=new Employee();

e.read();
//Serialization
out.writeObject(e);
out.close();

ObjectInputStream in=new ObjectInputStream(new FileInputStream("Employee.txt"));


// DeSerialization
Employee e1=(Employee) in.readObject();
e1.display();
in.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.

2. The Character Streams

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(ch!='q')//This loop gets interated as long as ch not equal to #


{
// place ch into the file
myOut.write(ch);
// read next character from keyboard
ch=(char)ir.read();
}
myOut.close();

//READING FROM FILE AND DISPLAY CONTENTs ON THE MONITOR


FileReadermyIn = new FileReader("input2.txt");
BufferedReaderbr=new BufferedReader(myIn);
System.out.println(" FILE READING: Contents of the file are");
int c;

while((c=br.read())!=-1)
System.out.print((char)c);
myIn.close();
}
}
2.5 BufferedReader

BufferedReaderimproves performance by buffering input. It has two constructors:

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

A BufferedWriteris a Writer that buffers ouput. Using a BufferedWritercan increase


performance by reducing the number of times data is actually physically written to the
output stream.
ABufferedWriterhas these two constructors:

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.

//Demonstration of BufferedReader and BufferedWriter .File copy using char 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 FileCopy
{
public static void main(String[] args) throws IOException
{
FileReader myIn = new FileReader("input2.txt");
BufferedReader br=new BufferedReader(myIn);
FileWriter myOut = new FileWriter("output2.txt");
int ch=br.read();
while(ch!=-1)
{
myOut.write(ch);
ch=br.read();
}
myIn.close();
myOut.close();
}
}

}
2.7 PrintWriter

PrintWriteris essentially a character-oriented version of PrintStream. It implements the


PrintWriterhas several constructors.
The following have been supplied by PrintWriterfrom the start:

PrintWriter(OutputStreamoutputStream)
PrintWriter(OutputStreamoutputStream, booleanflushOnNewline)
PrintWriter(Writer outputStream)
PrintWriter(Writer outputStream, booleanflushOnNewline)

Here, outputStreamspecifies an open OutputStreamthat will receive output. The


flushOnNewline

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.

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

2.8 StringReader and StringWriter

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.

Java StringReader Example

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.

The File object represents the actual file/directory on the disk

The following constructors can be used to create File objects:

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.

The following example demonstrates several of the File methods:

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

You might also like