You are on page 1of 16

OOPS USING JAVA UNIT-5

UNIT-5
INTRODUCTION

 Streams facilitate transporting data from one place to another.


 Various kinds of streams are required to receive data from different sources, and also to send data to
various places we need streams.
 Without streams, it is not possible to move data in java.

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.

Another classification of streams is: BYTE STREAMS & CHARACTER STREAMS.

 Byte stream represent the data in the form of individual bytes.


 If a class name ends with the word “stream” then it is said to be a byte stream class.
 InputStream and OutputStream reads and writes bytes.
Ex: FileInputStream, FileOutputStream, BufferedInputStream, BufferedOutputStream etc.,,,

 Character stream is also known as ‘text stream’.


 Text streams represent data as characters occupying 2 bytes of memory each.
 If a class names ends with the word ‘reader’ and ‘writer’ then it is taken as a text or character stream.
 Reader class reads the text and writer class writes the text.

DIFFERENCE BETWEEN BYTE AND CHARACTER STREAMS

 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.

Java I/O classes and Interfaces

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

FilterInputStream contains some more sub-classes like


a. BufferedInputStream
b. InflaterInputStream
c. LineNumberInputStream
d. DataInputStream

2. OutputStream
 ByteArrayOutputStream
 FileOutputStream
 PipedOutputStream
 ObjectOutputStream
 FilterOutputStream

FilterOutputStream contains some more sub-classes like


a. BufferedOutputStream
b. DeflaterOutputStream
c. PrintStream
d. DataOutputStream

IMPORTANT CLASSES OF CHARACTER STREAMS ARE:

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

THE BELOW GIVEN FIGURE SHOWS THE HIERARCHY OF STREAM CLASSES IN


JAVA

4
OOPS USING JAVA UNIT-5

Reading and Writing Files (UNIT-2) / Stream and Byte classes / Character Streams

Creating a file using FileOutputStream:

 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
}
}

In the above program,


1. Attach keyboard to DataInputStream class
2. Attach file1 to FileOoutputStream class
3. Read characters from dis into ch. Then write into fout.
4. Repeat step:3 till @ is typed.
5. Close the file.

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

IMPROVING EFFICIENCY USING BufferedOutputStream:

 Normally when we write data into file using FileOutputStream as:


fout.write(ch);
 In the above declaration we are calling the write() method on fout which is the object of
FileOutputStream class to write a character ch into file1.txt
 Let us assume that time taken to by DataInputStream class to read data from keyboard and write into
memory, is 1 second.
 Also, this character is written into file by using FileOutputStream and it takes another 1 second.
 Therefore, for reading and writing a single character it takes 2 seconds of time.
 So to read and write 200 characters it takes 200*2 = 400 seconds of time which is wasting lots of time.

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

In the above program buffer size is declared as 1024 bytes.


If buffer size is not specified then by default the size will be 512 bytes.

READING DATA FROM A FILE USING FileInputStream:

 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.

Program to read data from file2.txt using FileInputStream and display it

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.

Program to read data from any file

import java.io.*;
class readfile
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter file name whose contents are to be read");

String fname = br.readLine();


FileInputStream fin = null;
try
{
fin = new FileInputStream(fname);
}
catch(FileNotFoundException fe)
{
System.out.println("file is not found");
return;
}
BufferedInputStream bin = new BufferedInputStream(fin);
System.out.println("contents of the file are :");
int ch;
while((ch = fin.read())!= -1)
System.out.print((char)ch);
bin.close();
}
}
}

9
OOPS USING JAVA UNIT-5

Output:

Creating file using FileWriter:

FileWriter is useful to create a file by writing characters into it.

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

BufferedWriter bw = new BufferedWriter(fw,1024);


The above statement can be written to improve speed of execution.

READING A FILE USING FileReader:

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;

employee(int i,String n,float s, Date d)


{
id = i;
name = n;
sal = s;
doj = d;
}

void display()
{
System.out.println(id+" "+name+" "+sal+" "+doj);
}

12
OOPS USING JAVA UNIT-5

static employee getdata() throws IOException


{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter id");
int id = Integer.parseInt(br.readLine());
System.out.println("enter name");
String name = br.readLine();
System.out.println("enter salary");
float sal = Float.parseFloat(br.readLine());
Date d = new Date();
employee e = new employee(id,name,sal,d);
return e;
}
}
Output:

Program to show serialization of objects


import java.io.*;
import java.util.*;
class storeobject
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
FileOutputStream fos = new FileOutputStream("objfile");
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("How many objects are to be entered ?");
int n = Integer.parseInt(br.readLine());
for(int i =0;i<n;i++)
{
employee e1 = employee.getdata();
oos.writeObject(e1);
}
oos.close();
} }

13
OOPS USING JAVA UNIT-5

Output:

Program to show de-serialization of objects

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:

PRINT WRITER CLASS (UNIT-2)

o The Java.io.PrintWriter class prints formatted representations of objects to a text-output stream.

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.

o PrintWriter defines several constructors. The one we will use is shown here:


PrintWriter(OutputStream outputStream, boolean flushOnNewline)

o Here, outputStream is an object of type OutputStream, and flushOnNewline controls whether


Java flushes the output stream every time a newline ('\\n') character is output.
If flushOnNewline is true, flushing automatically takes place. If false, flushing is not
automatic.

o PrintWriter supports the print( ) and println( ) methods for all types including Object. Thus,


you can use these methods in the same way as they have been used with System.out. If an

15
OOPS USING JAVA UNIT-5

argument is not a simple type, the PrintWriter methods call the object's toString( ) method


and then print the result.

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:

Program to demonstrate PrintWriter  class


import java.io.*; 
public class PrintWriterDemo { 
public static void main(String args[]) { 
PrintWriter pw = new PrintWriter(System.out, true); 
pw.println("This is a string"); 
int i = -7; 
pw.println(i); 
double d = 4.5e-7; 
pw.println(d); 

}

o The output from this program is shown here:


o This is a string 
-7 
4.5E-7
o Remember, there is nothing wrong with using System.out to write simple text output to the
console when you are learning Java or debugging your programs. However, using
a PrintWriter will make your real-world applications easier to internationalize. Because no
advantage is gained by using a PrintWriter in the normal java programs. so we will continue to
use System.out to write to the console.

16

You might also like