Unit V
Unit V
Unit V
Course Material
Semester: III
Syllabus
. Unit V: Managing Input / Output Files in Java : Concepts of Streams- Stream Classes –
Byte Stream classes – Character stream classes – Using streams – I/O Classes – File
Class – I/O exceptions – Creation of files – Reading / Writing characters, Byte-Handling
Primitive data Types – Random Access Files.
The concept of sending data from one stream to another (like one pipe feeding into
another pipe) has made streams in Java a powerful tool for file processing.
2
Program Destination
Writes
Output streams
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.c. writes) it
to the destination (file).
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.
a) Byte stream classes that provide support for handling I/O operations on bytes.
b) Character stream classes that provide support for managing I/O operations on
characters.
Write
Output Reader
Input Classes
Stream Classes
Stream
Method Description
1. read() reads a byte from the input stream
2. read (byte b[]) reads an array of bytes into b
3. read(byte b[],int n,int m) reads m bytes into b starting from nth byte
4. available() gives number of bytes available in the input
5. skip(n) skips over n bytes from the input stream
6. reset() goes back to the begining of the stream
7. close() close the input stream
Note that the class DatalnputStream extends FilterInputStream and implements the
interface Data Input. Therefore, the DatalnputStream class implements the methods
described in DataInput in addition to using the methods of InputStream class. The Datalnput
interface contains the following methods:
a) readShort() f) readDouble()
b) readLine() g) readUTF()
c) readChar() h) readLong()
d) readBoolean() i) readInt()
e) readFloat()
4
Method Description
write() write a byte from the output stream
write (byte []b) writes all bytes in the array b to the output stream
write(byte b[],int n,int m) writes m bytes from array b starting from nth byte
close() close the output stream
flush() flushes the output stream
USING STREAMS
There are various types of input and output stream classes used for handling both the
16-bit characters and 8-bit bytes. Although all the classes are known as I/O classes, not all
of them are used for reading writing operations only. Some perform operations such as
buffering, filtering, data conversion, counting and concatenation while carrying out I/O tasks.
DataInput DataOutput
RandomAccessFile
INPUT/OUTPUT EXCEPTIONS
When creating files and performing I/O operations on them, the system may generate
i/o related exceptions. The basic i/o related exception classes and their functions are given
below.
Each I/O statement must have an exception handler around it as shown below:
try
{
.....................
. ........................ //I/O statements
.....................
}
catch (IOException e)
{
.................... // Message output statement
}
CREATION OF FILES
If we want to create and use a disk file, we need to decide the following about the file
and its intended purpose:
• Suitable name for the file
• Data type to be stored
• Purpose (reading, writing or updating)
• Method of creating the file
(i) A filename is a unique string of characters that helps identify a file on the disk. The length
of a filename and the characters allowed are dependent on the OS on which the java
program is executed. A file may consist of two parts, a primary name and an optional
period with extension.
9
Example:
Input.data Salary test.doc
student.txt
inventory rand.dat
(i) Data type is important to decide the type of file stream classes to be used for handling
the data. User should decide whether the data to be handled is in form of characters,
bytes or primitive type.
(i) The purpose of using a file must also be decided before using it. For example, user
should know whether the file is created for reading only, or writing only, or both the
operations.
The constructor, of stream classes may be used to assign the desired filenames to the file
stream objects.
There are two ways of initializing the file stream objects. All of the constructors
require that we provide the name of the file either directly, (as a literal string or variable), or
indirectly by giving a file object that has already been assigned a filename. The following
code segment illustrates the use of direct approach.
Example: Program to two file stream classes to copy the contents of a file named
“input.dat”into a file called “output.dat”.
{
public static void main (String args[])
{
file inFile=new file ("input.dat");
file outFile=new file ("output.dat");
FileReader ins=null;
FileWriter outs=null;
try
{
ins=new FileReader (inFile); //Opens inFile
outs=new FileWriter (outFile); //Opens outFile
//Read and write till the end
int ch;
while((ch=ins.read())!=-1)
{
outs.write(ch);
}
}
catch (IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally //Close files
{
try
{
ins.close();
outs.close ();
}
catch (IOException e)
{}
}
}
}
12
READING/WRITING CHARACTERS
The subclasses of Reader and Writer implement streams that can handle characters.
The two subclasses used for handling characters in files are FileReader and FileWriter.
The general form is
FileReader fileobject=new FileReader(filename);
FileWriter fileobject= new FileWriter(filename);
Method Description
read() reads a byte from the input stream
read (byte b[]) reads an array of bytes into b
read(byte b[],int n,int m) reads m bytes into b starting from nth byte
available() gives number of bytes available in the input
skip(n) skips over n bytes from the input stream
reset() goes back to the beginning of the stream
close() close the input stream
Method Description
write() write a byte from the output stream
write (byte []b) writes all bytes in the array b to the output stream
write(byte b[],int n,int m) writes m bytes from array b starting from nth byte
close() close the output stream
flush() flushes the output stream
Example: Program to two file stream classes to copy the contents of a file named
“input.dat”into a file called “output.dat”.
{
ins=new FileReader (inFile); //Opens inFile
outs=new FileWriter (outFile); //Opens outFile
//Read and write till the end
int ch;
while((ch=ins.read())!=-1)
{
outs.write(ch);
}
}
catch (IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally //Close files
{
try
{
ins.close();
outs.close ();
}
catch (IOException e)
{}
} } }
The character -1 indicates the end of the file and therefore the code
while ( (ch-ins.read( ) ) != -1)
causes the termination of the while loop 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 an I/0 exception, it prints a message and then exits from execution.
14
READING/WRITING BYTES
The FileReader and FileWriter classes is used to read and write 16-bits characters.
Two commonly used classes for handling bytes are FileInputStream and FileOutputStream
classes. This is used in place of FileReader and FileWriter.
The general form is
FileInputStream fileobject=new FileInputStream(filename);
FileOutputStream fileobject=new FileOutputStream(filename);
Method Description
read() reads a byte from the input stream
read (byte b[]) reads an array of bytes into b
read(byte b[],int n,int m) reads m bytes into b starting from nth byte
available() gives number of bytes available in the input
skip(n) skips over n bytes from the input stream
reset() goes back to the beginning of the stream
close() close the input stream
Method Description
write() write a byte from the output stream
write (byte []b) writes all bytes in the array b to the output stream
write(byte b[],int n,int m) writes m bytes from array b starting from nth byte
close() close the output stream
flush() flushes the output stream
The program demonstrates how FileOutputStream class is used for writing bytes to a
file. The writes to the names of some cities stored in a byte array to a new file named
"city.txt". User can verify the contents of the file by using the command
type city.txt
Explanation :
type city.txt
DELHI
MADRAS
LONDON
Program 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. We may use this program to read
the file "city.txt" created in Program 1.
import java.io.*;
class ReadBytes
{
public static void main (string args[])
{
//Create an input file stream
FileInputStream infile=null;
int b;
try
{
//Connect infile stream to the required file
infile=new FileInputStream(args[0]);
16
The basic input and output streams provide read/write methods that can be used for
reading/writing bytes or characters. If we want to read/write the primitive data types such
as integers and doubles.
The two filter classes used for creating "data streams" for handling primitive types
are DataInputStream and DataOutputStream.
A data stream for input can be created as follows:
FileInputStream fis=new FileInputStream (infile);
DataInputStream dis=new DataInputStream (fis);
These statements first create the input file stream fis and then create the input data
stream dis. These statements basically wrap dis on fis and use it as a "filter". Similarly, the
following statements create the output data stream dos and wrap it over the output file
stream fos.
FileOutputStream fos=new FileOutputStream (outfile);
DataOutputStream dos=new DataOutputStream (fos);
The file objects infile and outfile must be initialized with appropriate file names before
they are used.
17
Note that the file objects infile and outfile must be initialized with appropriate file names
before they are used. User may also use file names directly in place of files objects.
Output:
18
1999
375.85
false
X
Example:
import java.io.*;
class randomIO
{
public static void main (string args[])
{
RandomAccessFile file=null;
try
{
file=new RandomAccessFile ("rand.dat",”rw”);
file.WriteChar(„X‟);
file.WriteInt(555);
file.Writedouble(3.1412);
file.seek(0);
System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());
file.seek(2);
19
System.out.println(file.readInt());
file.seek(file.length());
file.WriteBoolean(false);
file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
catch(IOExceptiom e)
{
System.out.println(e);
}
}
}
The program opens a random access file and then performs the following operations.
1. Writes three items of data
X
555
3.1412
2. Brings the file pointer to the beginning.
3. Reads and displays all three items.
X
555
3.1412
4. Takes the pointer to the second item and then reads and displays the second item in the
file.
555
5. Places the pointer at the using the method length() and then add a Boolean item to the
file.
6. Finally, takes the pointer to the fourth item and displays it.
7. At the end, closes the file.
X
555
3.1412
555
false