Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 14

Page no- 1

UNIT-4 STREAMS
Q). What is a Stream?. Concept of stream.

Java uses the concept of streams to represent the ordered sequence of data, a common
characteristic shared by all the input/output devices. A stream presents a uniform, easy-to-use,
object-oriented interface between the program and the input/ output devices.

A stream in Java is path along which data flows (like a river or a pipe along which water flows). It
has a source (of data) and a destination (for the data). Both the source and the destination may
be physical devices or programs or other streams in the same program.

Java streams are classified into two basic types, namely, input stream and output stream. An
input stream extracts (i.e., reads) data from the source (file) and sends it to the program.
Similarly, an output stream takes data from the program and sends (i.e. writes) it to the
destination (file). The program connects and opens an input stream on the data source and then
reads the data serially. Similarly, the program connects and opens an output stream to the
destination place of data and writes data out serially.

Q). Briefly explain about stream classes?

The java.io package contains a large number of stream classes that provide capabilities for
processing all types of data. These classes may be categorized into two groups based on the data
type on which they operate.

1. Byte stream classes that provide support for handling I/O operations on bytes.

2. Character stream classes that provide support for managing I/O operations on characters.

These two groups may further be classified based on their purpose. Figure below shows how
stream classes are grouped based on their functions

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 2

1. Byte Stream classes:

It was designed to provide functional features for creating and manipulating streams and files
for reading and writing bytes. Byte stream are defined by using two classes, InputStream and
OutputStream.

a. Input Stream classes:

InputStream classes that are used to read 8-bit bytes, include a super class known as
InputStream and a number of sub classes for supporting various input related functions.

b. OutputStream classes:

OutputStream classes that are used to write 8-bit bytes, include a super class known as
OutputStream and a number of sub classes for supporting various output related functions.
16-bit unicode character. There are two kinds of character stream classes namely

2. Character Stream classes:

Character streams can be used to read and write reader stream classes and writer stream
classes.

a. Reader stream classes:

Reader stream classes are designed to read character from the files. Reader class is the base
class for all other classes in this group.

b. Writer stream classes:

Writer stream classes are designed to write all output operation on files. Writer class is the
base class for all other classes in this group. We can also cross-group the streams based on
the type of source or destination they read from or write to. The source(or destination) may
be memory, a file or a pipe.

Q). How to create a file using FileOutputStream? Explain with example?

FileOutputStream class belongs to byte stream and stores the data in the form of individual
bytes. It can be used to create text files. We know that a file represents storage of data on a
second storage media like a hard disk or CD. The following steps are to be followed to create a
text file that stores some characters (or text)

i) First of all, we should read data from the keyboard. For this purpose, we should attach the
keyboard to some input stream class. The code for using DatalnputStream class for reading
data from the keyboard is as:

DataInputStream dis= new DataInputStream(System.in);

Here, System.in represents the keyboard which is linked with DataInputStreamm object, that is, dis.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 3

ii) Now, attach a file where the data is to be stored to some output stream. Here, we take the
help of FileOutputStream which can send data to the file. Attaching the file myfile.txt to
FileOutputStream can be done as

FileOutputStream fout=new FileOutputStream ("myfile.txt");

In the above statement, fout represents the FileOutputStream object.

iii) The next step is to read data from DataInputStream and write it into FileOutputStream. It
means read data from dis object and write it into fout object, as shown here:

ch= (char) dis.read(); //read one character into ch

fout.write(ch); //write ch into file

Finally, any file should be closed after performing input or output operations on it, else the
data of the file may be corrupted. Closing the file is done by closing the associated streams.
For example, fout.close(); will close the FileOutputStream, hence there is no way to write
data into the file. These steps are shown in Figure and implemented in Program

Example: Creating a text file using FileOutputStream

import java.io.*;
class CreateFile
{
public static void main (String args[]) throws IOException
{
DataInputStream dis = new DataInputStream (System.in);
FileOutputStream fout = new FileOutputStream ("myfile.txt");
System.out.println("Enter text (@at the end);");
char ch;
while ((ch=(char)dis.read()) != '@')
fout.write(ch);
fout.close();
}
}
Output:
CA> javac createfile java
C:\> java createfile
enter text (@ at the end);
This is my life line one
This is my life line two

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 4

@
C: type myfile.txt
This is my file line one
This is my file line two.

Q). Explain about Reading data from a file using FileInputStream with example?

FileInputStream is useful to read data from a file in the form of sequence of bytes. It is possible
to read data from a text file using FileInputStream. Let us see how it is done:

1. First, we should attach the file to a FileInputStream as shown here:

FileInputStream fin = new FileInputStream ("myfile.txt");

This will enable us to read data from the file. Then, to read data from the file, we should read
data from the FileInputStream as :

Ch= fin.read ();

When the read() method reads all the characters from the file, it reaches the end of the file.
When there is no more data available to read further, the read() method returns -1.

2. For displaying the data, we can use System.out which is nothing but PrintStream object.

System.out.print(ch);

3. Finally, we read data from the FileInputStream and write it to System.out. This will display all
the file data on the screen.

These steps are shown in Figure and implementd in Program

Example: // Reading textfile using FileInputStream


import java.io.*;
class ReadFile
{
public static void main(String args[]) throws IOException
{
FileInputStream fin=new FileInputStream("myfile.txt");
while ((ch=fin.read()) != -1)
System.out.print((char)ch);
fin.close();
}
}

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 5

Output:

C:> java ReadFile.java


C:>java ReadFile File contents:
This is my third line
This is my file line four
This is last line

Q). Explain about writing character to a file and Reading character from a file with
examples.
(or)
Explain about File writer and FileReader classes with example?

Java provides two special types of stream called the FileReader and FileWriter to read
characters from file and write characters in to a file.

1. Writing characters to a file:

The FileWriter class can use to write characters to a file. FileWriter will create the file before
opening it for output when we create the object.

A FileWriter object can be created as follows:

FileWriter fo= new FileWriter(String filename); //Alternatively, it can be created as File


File Outfile = new File(String filename);
FileWriter fw= new FileWriter(outfile);

Methods of FileWriter class:

Method Description
1) public void write(String text) :writes the string into FileWriter.
2) public void write(char c) :writes the char into FileWriter.
3) public void write(char[] c) : writes char array into FileWriter.
4) public void close() : closes File Writer.

Example program for writing characters to a file:

import java.io.*;
class Simple {
public static void main(String args[])
{
try{
FileWriter fw= new FileWriter("abc.txt");
fw.write("my name is sachin");
fw.close();
}

catch(Exception e)
{System.out.println(e);}
System.out.println("success");

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 6

}
Output: success...

2. Reading character from a file:

The FileReader class that we can use to read characters from a file. A FileReader object can be
created as follows

FileReader fi= new FileReader(String filename); //Alternatively, it can be created as


File infile = new File(string filename);
FileReader Fi= new FileReader(infile);

Methods of FileReader class:


Method Description

1) public int read() : returns a character in ASCII form. It returns-1 at the end of file.
2) public void close() : closes FileReader.

Example program for reading characters from a file :

import java.io.*;
class Simple {
public static void main(String args[]) throws Exception
{
FileReader fr = new FileReader ("abc.txt");
int i;
While(i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}
}

Output:
my name is sachin

Q). Explain about Zipping a File?

Let us now learn how to compress data in a file, say 'file' by following these steps:

i) Attach the input file 'file' to FileInputStream for reading data.

ii) Take the output file 'file2' and attach it to FileOutputStream. This will help to write data
into 'file2'.

iii) Attach FileOutputStream to DeflaterOutputStream for compressing the data.

iv) Now, read data from FileInputStream and write it into DeflaterOutputStream. It will
compress the data and send it to FileOutputStream which stores the compressed data
into the output file. These steps are shown in Figure and implemented in Program

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 7

Example: //Compressing a file using a DeflaterOutputStream

import java.io.*;
import java.util.zip.*;
class Zip
{
public static void main (String args[]) throws Exception{
// FileInputStream for reading data
FileInputStream fis = new FileOutputStream("files1")
FileOutputStream fos=nes FileOutputStream ("file2")
DeflaterOutputStream dos = new DeflaterOutputStream(fos);
fis.close();
int data;
while ((data = fis.read()) != -1)
dos.write (data);
fis.close();
dos.close();
}

Output:
C:\> javac Zip.java
C:\> java Zip

Q). Explain about unzipping a file?

The file with the name 'file2' contains compressed data and suppose we want to obtain original
uncompressed data from this file. Let us follow these steps to data from this file.

i) Attach the compressed file 'file2' to FileInputStream. This helps to read data from 'file2'

ii) Attach the output file file3' to FileOutputStream. This will help to write uncompressed
data into 'file3".

iii) Attach FileInputStream to InflaterInputStream so that the data read from FileInputStream
goes into InflaterInputStream. Now InflaterInputStrea uncompresses the data.

iv) Now, read uncompressed data from InflaterInputStream and write it into
FileOutputStream. This will write the uncompressed data to 'file3'. These steps are shown
in Figure below and are implemented in Program.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 8

Example: Program to uncompress data from a compressed file by using InflaterInputStream.

import java.io.*;
import java.util.zip.*;
class unzip
{
public static void main (String args[]) throws Exception
{
FileInputStream fis= new FileInputStream ("file2");
FileOutputStream fos= new FileOutputStream ("file3");
InflaterInputStream iis = new InflaterInputStream(fis);
int data;
while ((data = iis.read()) != -1)
fos.write(data);
fos.close();
}
}

Q). Briefly explain about serialization of Objects?

So far, we wrote some programs where we stored only text into the files and retrieved same
text from the files. These text files are useful when we do not want to perform any calculations
on the data.

For example, we want to store some employee details like employee identification number (int
type), name (String type), salary (float type) and date of joining the job (Date type) in a file. This
data is well structured and got different types. To store such data, we need to create a class
Employee with the instance variables id, name, sal, doj as shown here:

class Employee implements Serializable


{
//instance var
private int id;
private String name;
private float sal;
private Date doj;}

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 9

Then create an object to this class and store actual data into that object. Later, this object
should be stored into a file using objectOutputStream. Observe that the Serializable interface
should be implemented by the class whose objects are to be stored into the file. This is the
reason why Employee class implements Serializable interface.

To store the Employee class objects into a file, follow these steps:

i) First, attach objfile to FileOutputStream. This helps to write data into objfile.

FileOutputStream fos = new FileOutputStream("objfile")

ii) Then, attach FileOutputStream to ObjectOutputStream.

ObjectOutputStream oos = new objectOutputStream(fos).

iii) Now, ObjectOutputSteam can write objects using writeObject() method to FileOutputStream,
which stores them into the objfile.

Storing objects into a file like this is called 'serialization'. The reverse process where objects can be
retrieved back from a file is called 'de-serialization'.

Program: Write a program to create Employee class whose objects are to be stored into a file.

//Employee class
import java.io.*;
import java.util.Date;
class Employee implements Serializable
{
private int id;
private Straing name;
private float sal;
private Date doj;
Employee (int i, String n, float s, Date d)
{
Id=i;
Name=n:
Sal=s;
Doj=d;
}
System.out.println(id+"\t"+name+"\t"+doj);
static Employee getData() throws IOExecption
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in);
System.out.print("Enter emp id: ") ;
int id= Integer.parseInt(br.readLine());
System.out.print ("Enter name: ");
String name = br.readLine();
Date d= new Date();

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 10

Employee e= new Employee (id, name, sal, d);


return e;
}
}

Output:
C>javac Employee.java

Program: Write a program to show serialization of objects.


//objectoutputStream is used to store objects to a file
import java.io.*;
import java.util.*;
class StoreObj
{
public static void main (String args[]) throws Exception
{
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
FileOutputStream fos = new FileOutputStream("objfile") ;
ObjectOutputStream oos = new ObjectOutputStream(fos) ;
System.out.print ("How may objects?") ;
int n = Integer.parseInt(br.readLine());
for (int i=0; i<n; i++)
{
Employee el-=Employee.getData();
oos.writeobject(el);
}
oos.close();
}
}

Output:
C: javac Storeobj.java
C>java Storeobj

How many objects ? 3


Enter emp id: 10
Enter name: Rohith
Enter salary: 9800.50
Enter emp id: 11
Enter name: Rohan
Enter salary: 8000.00

Q). Explain about counting number of characters in a File?

Write a program which accepts a filename from command line argument and displays the
number of charaters, words, and lines in the file.

//Counting no. of chars in a text file


import java.io.*;
class Count
{
public static void main(String args[]) throws IOException

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 11

{
int ch;
boolean prev= true;
int char_count=0; int line_count=0;
int word_count=0;
FileInputStream fin= new FileInputStream (args [0]);
while ((ch=fin.read()) != -1)
{
if (ch !=’ ‘) ++char_count ;
if (!prev && ch==' ')++word_count;
if (ch==' ') prev=true; else prev= false;
if (ch=='\n')++line_count;
}
char_count=line_count*2;
word count+=line_count;
System.out.println ("No. of chars="+char_count);
System.out.println("No. of words="+word_count);
System.out.println("No. of lines="+ line_count);
fin.close();
}
}

Output:
C:\> javac Count.java
C:\> java Count myfile No. of chars = 44
No. of words=12
No. of lines=6

Q). Briefly explain File copy with example?

Sometimes we need to copy the entire data of a text file into another text file. Streams are useful
in this case. To understand how to use streams for copying a file content to another file, we can
use the following logic:

i) For reading data form the input file, attach it to FileInputStream.

ii) For writing data into the output file, which is to be created, attach it to
FileOutputStream.

Example: Write a program to read the contents of the input file and write them into an output
file..

//Copying a file contents as another file.

import java.io.*;
class CopyFile
{
public static void main (String args[]) throws loXeception
{
int ch;
FileInputStream fin = new FileInputStream(args[0]);

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 12

FileoutStream fout = new FileoutputStream (args[0]);


while ((ch=fin.read ()) != -1)
fout.write (ch);
fin.close();
fout.close();
System.out.println("I file copied");
}
}
Output:
C: javac CopyFile.java
ile car gif carl1.gif
I file copied

Q). Briefly explain about File class and Methods with example?

1. File Class

File class of java.io package provides some methods to know the properties of a file or a
directory. First of all, we should create the File calss object by passing the filename or directory
name to it.

File obj =new File (filename);


File obj=new File (directoryname);
File obj=new File ("path", filenmae);
File obj = new File ("path", directoryname);

2. File Class Methods

File class includes the following methods:

1. boolean is File (): This method returns true if the File object contains a filename, otherwise
false.

2. boolean isDirectory(): This method returns true if the File objects contains a directory name.

3. boolean canRed (): This method returns true if the File object contains a file which is
rendable.

4. boolean can Write (): This method returns true if the file is writable.

5. boolean canExecute (): This method returns true if the file is executable.

6. boolean exists(): This method returns true when the File object contains a file or directory
which physically exists in the computer

7. String getParent (): This method gives the name of directrory path of a file or directory.

8. String getPath(): This method gives the name of directory path of a file or directory.

9. Stirng getAbsolutePath(): This method gives the absolute directory path of a file or directory
location. Absolute paaath is mentioned staarting from the root directory.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 13

10. long length(): This method returns a number that represents the size of the file in bytes.

11. boolean delete (): This method deletes the file or directory whose name is in File object.

12. boolean createNewFile(): This method automatically creates a new, empty file indicated by
File object, if and only if a file with this name does not yet exist.

13. boolean mkdir (): This method creates the directory whose name is given in File object.

14. boolean rename To (File newname): This method charges the name of the file as new name.

15. String[] list (): This method returns an array of strings naming the files and directories in the
directory.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 14

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science

You might also like