U4 Java2
U4 Java2
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.
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
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.
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
Character streams can be used to read and write reader stream classes and writer 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.
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.
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:
Here, System.in represents the keyboard which is linked with DataInputStreamm object, that is, dis.
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
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:
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
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
@
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:
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 :
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.
Output:
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.
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.
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.
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");
}
Output: success...
The FileReader class that we can use to read characters from a file. A FileReader object can be
created as follows
1) public int read() : returns a character in ASCII form. It returns-1 at the end of file.
2) public void close() : closes FileReader.
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
Let us now learn how to compress data in a file, say 'file' by following these steps:
ii) Take the output file 'file2' and attach it to FileOutputStream. This will help to write data
into 'file2'.
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
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
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.
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();
}
}
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:
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.
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();
Output:
C>javac Employee.java
Output:
C: javac Storeobj.java
C>java Storeobj
Write a program which accepts a filename from command line argument and displays the
number of charaters, words, and lines in the file.
{
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
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:
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..
import java.io.*;
class CopyFile
{
public static void main (String args[]) throws loXeception
{
int ch;
FileInputStream fin = new FileInputStream(args[0]);
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.
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.
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.