Professional Documents
Culture Documents
Bhandare
Chapter 6
Managing input & output files in
java
-by-
Prof. Bhandare P. S.
SVERI’s COE(Poly), Pandharpur
Hours: 06
Marks: 08
Subject Name: - Java Programming (22412) 1 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Syllabus:
1. Introduction and Concept of Streams.
2. Stream Classes.
3. Byte Stream Classes: Input Stream Classes, Output Stream Classes.
4. Character Stream Classes, Using streams.
5. Using File Class: I/O Exceptions, Creation of Files, Reading/Writing
characters, Reading/Writing Bytes, Handling Primitive Data types.
Assignment no. 5
6. Write any four methods of file class with their use.(4M)(S-17)
7. What is Iterator class ? Give syntax and use of any two methods of Iterator
class.(4M) (S-17)
8. What is use of ArrayListclass ? State any two methods with their use from
ArrayList. (4M) (S-17)
9. Draw the hierarchy of Writer stream classes, and hierarchy of Reader stream
classes.(4M)(w-16)
10.Explain methods of map class and set class in jdk frame work. (4M) (w-16)
(s-16)
11.What are stream classes ? List any two input stream classes from character
stream.(4M) (s-16)
12.Explain serialization with stream classes.(4M) (s-16)
13.What are streams ? Write any two methods of character stream
classes.(4M)(w-15)
14.Write any two methods of File and FileInputStream class each.(4M)(w-15)
15.Write syntax and function of following methods of Date class : (4M)(s-15)
1. i) getTime( )
2. ii) getDate ()
Subject Name: - Java Programming (22412) 2 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Programs
Subject Name: - Java Programming (22412) 3 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Introduction
So far we have used variables and arrays for storing data inside the programs.
This approach poses the following problems.
1. The data is lost either when a variable goes out of scope or when the
program is terminated. That is, the storage is temporary.
2. It is difficult to handle large volumes of data using variables and
arrays.
We can overcome these problems by storing data on secondarystorage
devices such as floppydisks or harddisks.
The data is stored in these devices using the concept of files.
Datastored in files is often called persistentdata.
A file is a collection of relatedrecords placed in a particular area on the disk.
A record is composed of several fields and a field is a group of characters as
illustrated in Fig.
Characters in JavaareUnicodecharacters composed of twobytes, each byte
containing eight binary digits, 1 or 0.
Storing and managing data using files is known as fileprocessing which
includes tasks such as creatingfiles, updatingfiles and manipulation of data.
Reading and writing of data in a file can be done at the level of bytes or
characters or fields depending on the requirements of a particular application.
Java also provides capabilities to read and write class objects directly.
Note that a record may be represented as a classobject in Java.
The process of reading and writing objects is called objectserialization.
Concept of Streams
In file processing, input refers to the flow of datainto a program and output
means the flow of dataout of a program.
Subject Name: - Java Programming (22412) 4 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Input to a program may come from the keyboard, the mouse, the memory,
the disk, a network, or anotherprogram.
Similarly, output from a program may go to the screen, the printer, the
memory, the disk, a network, or anotherprogram.
This is illustrated in Fig. below
Keyboard Keyboard
Mouse Mouse
Memory Memory
Java
Program
Disk Disk
Network Network
Program Program
Inpu
Outpu
t
t
Although these devices look very different at the hardware level, they share
certain common characteristics such as unidirectionalmovement of data,
treating data as a sequence of bytes or characters and support to the
sequentialaccess to the data.
Java uses the concept of streams to represent the orderedsequence of data a
common characteristic shared by all the inputoutput devices as stated above.
A stream presents a uniform, easy-to-use, object-oriented interface between
the program and the input/output devices.
A stream in Java is a path along which dataflows (like a river or a pipe along
which water flows).
It has a source (of data) and a destination (for that data) as depicted in Fig.
below.
Both the source and the destination may be physicaldevices or programs or
other streams in the same program.
Subject Name: - Java Programming (22412) 5 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
The concept of sendingdata from one stream to another (like one pipe
feeding into another pipe) has made streams in Java a powerful tool for
fileprocessing.
We can build a complexfile processing sequence using a series of simple
streamoperations.
This feature can he used to filter data along the pipeline of streams so that we
obtain data in a desiredformat.
For example, we can use one stream to get rawdata in binary format and then
use another stream in series to convert it to integers.
Javastreams are classified into two basic types, namely, inputstream and
outputstream.
An inputstreamextracts (i.e. reads) data from the source (file) and sends it
to the program. Similarly, an outputstreamtakes data from the program and
sends (i.e. writes) it to the destination (tile).
Figure below illustrates the use of input and output streams.
The program connects and opens an Inputstream on the data source and then
reads the dataserially.
Similarly, the program connects and opens an outputstream to the
destinationplace of data and writesdata out serially.
In both the cases, the program does not know the details of endpoints (i.e.
source and destination).
Subject Name: - Java Programming (22412) 6 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Stream Classes
The java.io package contains a large number of streamclasses that provide
capabilities for processing all types of data.
These classes may be categorized into twogroups based on the data type on
which they operate.
1. Bytestream classes that provide support for handlingI/O operations
on bytes.
2. Characterstream 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
Subject Name: - Java Programming (22412) 7 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Object
Input Stream
FileInputStream
SequenceInputStream
PipeInputStream
ObjectInputStream
ByteArrayInputStream
StringBufferInputStream
FilterInputStream
BufferedInputStream PushbackInputStream
DataInputStream
DataInput
Subject Name: - Java Programming (22412) 8 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
3. read (byte b[], int n, int m) Reads m bytes into b starting from nth byte
Subject Name: - Java Programming (22412) 9 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Object
Output Stream
FileOutputStream
ByteArrayOutputStream
PipeOutputStream
ObjectOutputStream
FilterOutputStream
BufferedOutputStream PushbackOutputStream
DataOutputStream
DataOutput
Subject Name: - Java Programming (22412) 10 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Method Description
1. Write() Writes a byte to the output stream
2. write(byte b[]) Writes all bytes in the army b to the output stream
3. writc(byte b[]. int n, int m) Writes m bytes from way b starting from nth byte
4. close( ) Closes the output stream
5. flush( ) Flushes the output stream
Subject Name: - Java Programming (22412) 11 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Some of these methods along with their description are listed in Table.
Method Description
intread() returns the integral representation of the next available
character of input. It returns -1 when end of file is
encountered
int read (char buffer []) attempts to read buffer. length characters into the buffer and
returns the total number of characters successfully read. It
returns -I when end of file is encountered
int read (char buffer [], attempts to read 'nChars' characters into the buffer starting
intloc, intnChars) at buffer [loc] and returns the total number of characters
successfully read. It returns -1 when end of file is
encountered
void mark(intnChars) marks the current position in the input stream until 'nChars'
characters are read
Subject Name: - Java Programming (22412) 12 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
void reset () resets the input pointer to the previously set mark
long skip (long nChars) skips 'nChars' characters of the input stream and returns the
number of actually skipped characters
boolean ready () returns true if the next request of the input will not have to
wait, else it returns false
void close () closes the input source. If an attempt is made to read even
after closing the stream then it generates IOException
Writer Classes
Writerclasses are used to write16-bit Unicode characters onto an
outputstream.
The Writer class is the superclass for all character-oriented output stream
classes .
All the methods of this class throw an IOException.
Being an abstract class, the Writer class cannot be instantiated hence, its
subclasses are used.
WriterStream Classes Like outputstream claws, the writer stream classes are
designed to perform all outputoperations on files.
Only difference is that while outputstream classes are designed to write bytes,
the writerstream classes art designed to writecharacters.
This base class provides support for all output operations by defining
methods that are identical to those in OutputStreamclass.
Subject Name: - Java Programming (22412) 13 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Subject Name: - Java Programming (22412) 14 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Subject Name: - Java Programming (22412) 15 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Subject Name: - Java Programming (22412) 16 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Subject Name: - Java Programming (22412) 17 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
fis ABC.txt
Reading/Writing Characters
As pointed out earlier, subclasses of Reader and Writer implement streams
that can handle characters.
The two subclasses used for handling characters in files are FileReader (for
reading characters) and FileWriter (for writing characters).
Following program demonstrate reading data from file.
Program for reading characters from file
Subject Name: - Java Programming (22412) 18 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Subject Name: - Java Programming (22412) 19 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
This program is very simple. It creates two file objects inFile and outFile and
initializes them with "input.dat" and "output.dat” respectively using the
following code.
File inFile = new File (“input.dat");
FlleoutFile = new File (“output.dat");
The program then creates two file stream objects ins and outs and initializes
them with "null" as follows:
FileReader ins = null;
FileWriter outs = null;
These streams are then connected to the named files using the following code:
ins = new FileReader (inFile);
outs = new FileWriter (outFile);
This connects inFile to the FileReaderstream ins and outFile to the
FileWriter stream outs.
This essentially means that the files "input.dat" and "output.dat" are opened.
The statements ch = ins.read ( ) .
reads a character from the inFile through the input stream Ins and assigns it
to the variable ch.
Similarly, the statement outs.write (ch) writes the character stored in the
variable ch to the outFile through the outputstreamouts.
The character -1 indicates the endofthefile and therefore the code while (
(ch=ins.read( ) ) -1)
causes the lamination of the whileloop when the end of the file is reached.
The statements
ins.close ( )
outs.close ( )
enclosed in the finally clause close the files created for reading and writing.
When the program catches anI/O exception, it prints a message and then exits
from execution.
Reading/Writing Bytes
In Program we have used FileReader and FileWriter classes to read and write
16-bitcharacters.
However, most file systems use only 8-bitbytes.
As pointed out earlier, JavaI/O system provides a number of classes that can
handle 8-bit bytes.
Two commonly used classes for handling bytes are FileInputStream and
FileOutputStream classes.
Subject Name: - Java Programming (22412) 20 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Subject Name: - Java Programming (22412) 21 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
The program writes the names of some cities stored in a bytearray to a new
file named "city.txt".
We can verify the contents of the life by using the command
type city.txt
import java.io.*;
class writeBytes {
public static void main(String arr[]){
byte
cities[]={'M','A','D','R','A','S','\n','G','O','A','\n','P','U','N','E','\n','M','U
','M','B','A','I'};
FileOutputStreamfout=null;
try{
fout=new FileOutputStream("city.txt");
fout.write(cities);
fout.close();
}
catch(Exception e){
System.out.println(e);
System.exit(-1);
}
}
}
Note that a instantiating a FileOutputStream object with the name of the file
creates and opens the file.
We may also supply the filename as a command line argument at the time of
execution.
Remember, there are several forms of write( ) method.
The one we have used here writes the entirebyte array to the file. Finally, we
close the file opened for writing.
Program below shows how FilelnputStream class is used for reading bytes
from a file.
The program reads an existing file and displays its bytes on the screen.
Remember, before we run this program, we must first create a file for it to
read.
import java.io.*; public static void main(String
class readbytes { arr[])
Subject Name: - Java Programming (22412) 22 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
{ }
FileInputStream fin=null; fin.close();
int b; }
Try { catch(Exception e)
fin=new {
FileInputStream(arr[0]); System.out.println(e);
while((b=fin.read())!=- System.exit(-1);
1) }
{ }
System.out.print((char)b); }
Note that the program requires the filename to be given as a command line
argument.
Program displays the following when we supply the filename "city.txt".
Prompt>java readbytes city.txt
MADRAS
GOA
PUNE
MUMBAI
Another example code given in Program below uses both FlielnputStream
and FileOutputStream classes to copyfiles.
We need to provide a sourcefilename for reading and a targetfilename for
writing.
In the example code, we have supplied file namesdirectly to the constructors
while creatingfilestreams.
We may also supply them as commandlinearguments.
in.txt file contains data that is to copied in to out.txt;
import java.io.*;
class copybytes{
public static void main(String arr[]){
FileInputStream fin=null;
FileOutputStreamfout=null;
byte b;
try{
fin=new FileInputStream("in.txt");
fout=new FileOutputStream("out.txt");
do {
Subject Name: - Java Programming (22412) 23 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
b=(byte)fin.read();
fout.write(b);
}while(b!=-1);
fin.close();
fout.close();
}
catch(FileNotFoundExceptionfe){
System.out.print(fe);
}
catch(Exception e){
System.out.println(e);
System.exit(-1);
}
}
}
Program creates fin and fout streams for handling the input/output operations.
The program then continuously reads a byte from "in.txt" file (using
finstream) and writes it to "out.txt" file (using foutstream) until the end of
file condition is reached.
We should avoid writing to an existingtile.
We may use the exists( )method in the Fileclass to check whether the named
file alreadyexists.
Example:
File fout= new File ("out.dat");
if (fout.exists ( ) ) return ( )
This program could also be written using FileReader and FileWriter classes.
Handling Primitive Data Types
These classes use the concept of multipleinheritance as illustrated in Fig.
below and therefore implements all the methods contained in both the parent
class and the interface.
A data stream for input can be created as follows:
FileInputStreamfis = new FilelnputStream (infile);
DataInputStream dis = new DetalnputStream (fis) ;
These statements first create the input file stream fis and then create the input
data stream dis.
Subject Name: - Java Programming (22412) 24 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare
Subject Name: - Java Programming (22412) 25 Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.
Serializing an Object
• Writing Object to file is called as serialization.
1. import java.io.*;
2. class Employee implements Serializable
3. {
4. public String name;
5. public String address;
6. public int number;
7. }
8. public class SerializeDemo {
9. public static void main(String [] args) {
10. Employee e = new Employee();
11. e.name = "AAA";
12. e.address = "Pandharpur";
13. e.number = 101;
14. try {
15. FileOutputStream fileOut =
16. new FileOutputStream("object.txt");
17. ObjectOutputStream out = new ObjectOutputStream(fileOut);
18. out.writeObject(e);
19. out.close();
20. fileOut.close();
26
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.
27
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.
It is also possible to perform input and output operations on objects using the
object streams.
The object streams are created using the ObjectInputStream and
ObjectOuptutStream classes.
In this case, we may declare records as objects and use the object classes to
write and read these objects from files.
As mentioned in the beginning, this process is known as object serialisation.
Piped Streams
Pipedstreams provide functionality for threads to communicate and
exchange data between them.
Figure below shows how two threads use pipes for communication.
The write thread sends data to the read thread through a pipeline that connects
an object of PipedlnputStream to an object of PipedOutputStmtm.
The objects inputPipe and outputPipe are connected using the connect( )
method.
28
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.
29
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.
30
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.
System.out.println(dis.re dis.close();
adBoolean()); fin.close();
System.out.println(dis.re }
adDouble()); catch(IOException e){ }
System.out.println(dis.re }
adChar()); }
Other Stream Classes
Object Streams
We have seen in this chapter how we can read and write characters, bytes, and
primitive data types.
It is also possible to perform input and output operations on objects using the
object streams.
The object streams are created using the ObjectInputStream and
ObjectOuptutStream classes.
As mentioned in the beginning, this process is known as object serialisation.
Piped Streams
Pipedstreams provide functionality for threads to communicate and
exchange data between them.
Figure below shows how two threads use pipes for communication.
The write thread sends data to the read thread through a pipeline that connects
an object of PipedlnputStream to an object of PipedOutputStmtm.
The objects inputPipe and outputPipe are connected using the connect( )
method.
31
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.
Filtered Streams
Java supports two abstract classes, namely, FilterInputStream and
FilterOutputStream that provide the basic capability to create input and
output streams for tittering input output in a number of ways.
These streams, known as filters. sit between an input stream and an output
stream and perform some optional processing on the data they transfer.
We can combine filters to perform a series of filtering operations as shown in
Fig. below.
Note that we used DatalnputStream and DataOutputStream as filters in the
revious Program for handling primitive type data.
32
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java