UNIT-5: Oops Using Java UNIT-5
UNIT-5: Oops Using Java UNIT-5
UNIT-5: Oops Using Java UNIT-5
UNIT-5
INTRODUCTION
STREAM:
Stream carries data just as a water pipe carries water from one place to another place.
Streams can be classified as “input streams” and “output streams”.
Input streams are used to accept data, where as output streams are used to send data.
All streams are represented by classes in java.io package.
Byte streams are used to handle any characters like text, images, audio and video files.
Example: for storing any image of .jpg or.jpeg extension we can use byte stream.
Character streams can always store and retrieve data in form of characters only. That means, text streams
are more suitable to handle text files.
Example: text we create in notepad.
IMPORTANT CLASSES OF BYTE STREAMS ARE: java.io.InputStream and java.io.OutputStream. these are
abstract base classes for many subclasses.
1. InputStream
ByteArrayInputStream
FileInputStream
PipedInputStream
ObjectInputStream
FilterInputStream
1
OOPS USING JAVA UNIT-5
2. OutputStream
ByteArrayOutputStream
FileOutputStream
PipedOutputStream
ObjectOutputStream
FilterOutputStream
1. Reader
BufferedReader ( has another sub-class LineNumberReader)
CharArrayReader
FilterReader
InputStreamReader ( has another subclass FileReader)
PipedReader
StringReader
2. Writer
BufferedWriter
CharArrayWriter
FilterWriter
OutputStreamWriter ( has another sub-class FileWriter)
PipedWriter
PrintWriter
StringWriter
2
OOPS USING JAVA UNIT-5
The above figure shows the various kinds of input and output stream classes.
3
OOPS USING JAVA UNIT-5
4
OOPS USING JAVA UNIT-5
Reading and Writing Files (UNIT-2) / Stream and Byte classes / Character Streams
FileOutputStream class belongs to byte stream and stores data in the form of individual bytes.
It can be used to create text files.
File represents the storage of data on a secondary storage device like hard disc or CD.
Program to demonstrate how to read data from keyboard and write it to text file
import java.io.*;
class createfile
{
public static void main(String[] args) throws IOException
{
DataInputStream dis = new DataInputStream(System.in); //1
FileOutputStream fout= new FileOutputStream("file1.txt"); //2
System.out.println("enter @ at end");
char ch;
while((ch=(char)dis.read())!='@') //3
fout.write(ch); //4
fout.close(); //5
}
}
Output:
5
OOPS USING JAVA UNIT-5
If the above program is executed again the previous data whatever is written into the file1.txt will be overridden the
latest input data.
To avoid this:
FileOutputStream fout= new FileOutputStream("file1.txt",true); //2
When above statement is used even though the program is executed several times each time new data is
appended to the old data.
6
OOPS USING JAVA UNIT-5
If we use Buffered classes, they provide a “buffer” which is a temporary block of memory.
Buffer is first filled by the characters and then all the characters from the buffer can be written into
file at once.
Buffered classes can always be used in connection along with other stream classes.
Example is, BufferedOutputStream can be used laong with FileOutputStream to write data into a
file.
First, time taken to by DataInputStream class to read data from keyboard and write into memory,
is 1 second. So for 200 characters it takes 200 seconds of time.
Then, when buffer is full entire data is written into file at once which takes another 1 second of
time. So total time for reading and writing 200 characters is 201 seconds.
In the same way Buffered Classes can be used to improve reading of data.
Program to demonstrate how to read data from keyboard and write it to text file
( using BufferedOutputStream class)
import java.io.*;
class createfile
{
public static void main(String[] args) throws IOException
{
DataInputStream dis = new DataInputStream(System.in);
FileOutputStream fout = new FileOutputStream("file2.txt",true);
BufferedOutputStream bout = new BufferedOutputStream( fout, 1024);
System.out.println("enter @ at end");
char ch;
while((ch=(char)dis.read())!='@')
bout.write(ch);
bout.close();
}
}
Output:
7
OOPS USING JAVA UNIT-5
FileInputStream is useful to read data from a file in the form of sequence of bytes.
It is possible to read data from text file using FileInputStream class.
import java.io.*;
class readfile
{
public static void main(String[] args) throws IOException
{
FileInputStream fin = new FileInputStream("file2.txt");
System.out.println("contents of the file are :");
int ch;
while((ch = fin.read())!= -1)
System.out.print((char)ch);
fin.close();
}
}
Output:
8
OOPS USING JAVA UNIT-5
The above program can read the contents from file2.txt only.
In order to make the program to read contents of any file the file name should be accepted at run time.
For this, make use of InputStreamReader and BufferedReader classes.
import java.io.*;
class readfile
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
9
OOPS USING JAVA UNIT-5
Output:
import java.io.*;
class createfile1
{
public static void main(String[] args) throws IOException
{
String str = "this is java programming language" +"\nam studying about streams & files";
FileWriter fw = new FileWriter("text");
BufferedWriter bw = new BufferedWriter(fw,1024);
for(int i =0; i<str.length(); i++)
bw.write(str.charAt(i));
bw.close();
}
}
Output:
10
OOPS USING JAVA UNIT-5
import java.io.*;
class readfile1
{
public static void main(String[] args) throws IOException
{
int ch;
FileReader fr = null;
try
{
fr =new FileReader("text");
}
catch(FileNotFoundException fe)
{
System.out.println("file not found");
return;
}
while((ch=fr.read())!=-1)
System.out.print((char)ch);
fr.close();
}
}
Output:
11
OOPS USING JAVA UNIT-5
SERIALIZATION
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
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 serializes the object and transmits it.
The receiving machine deserializes it.
Serializable Interface:
The class whose objects are stored in the file should implement ‘Serializable’ interface of java.io package.
Serializable interface is an empty interface without any members in it.
It does not contain any methods also.
Such an interface is called as ‘marking interface’ or ‘tagging interface’.
This interface marks objects of class as serializable so that they can be written into a file.
If serializable interface is not implemented by the class then writing that class objects into a file will lead
to NotSerializableException.
Static and transient variables of the class cannot be serialized.
The below given set of programs will demonstrate the concept of serialization and de-serialization.
Program to create employee class whose objects are to be stored into a file
import java.io.*;
import java.util.Date;
class employee implements Serializable
{
private int id;
private String name;
private float sal;
private Date doj;
void display()
{
System.out.println(id+" "+name+" "+sal+" "+doj);
}
12
OOPS USING JAVA UNIT-5
13
OOPS USING JAVA UNIT-5
Output:
import java.io.*;
class getobject
{
public static void main(String[] args) throws Exception
{
FileInputStream fis = new FileInputStream("objfile");
ObjectInputStream ois = new ObjectInputStream(fis);
try
{
employee e;
while((e=(employee) ois.readObject())!=null)
{
e.display();
}
}
catch(EOFException ee)
{
System.out.println("end of file reached");
}
finally
{
14
OOPS USING JAVA UNIT-5
ois.close(); } } }
Output:
o Although using System.out to write to the console is still permissible under Java, its use is
recommended mostly for debugging purposes or for sample programs, such as those found in this
book. For real-world programs, the recommended method of writing to the console when using
Java is through a PrintWriterstream. PrintWriter is one of the character-based classes. Using a
character-based class for console output makes it easier to internationalize your program.
15
OOPS USING JAVA UNIT-5
o To write to the console by using a PrintWriter, specify System.out for the output stream and
flush the stream after each newline. For example, this line of code creates a PrintWriter that is
connected to console output:
o PrintWriter pw = new PrintWriter(System.out, true);
o The following application illustrates using a PrintWriter to handle console output:
16