0% found this document useful (0 votes)
6 views

Unit V

Java

Uploaded by

yugabharath852
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit V

Java

Uploaded by

yugabharath852
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

1

Unit V
Course Material

Subject: Core V : Java Programming Class: II B.Sc CS A

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.

MANAGING INPUT / OUTPUT FILES IN JAVA: CONCEPTSOFSTREAMS


In file processing, input refers to the flow of data into a program and output means
the flow of data out of a program. Input to a program may come from the keyboard, the
mouse, the memory, the disk, a network or another program. Similarly, output from a
program may go to the screen, the printer, the memory, the disk, a network or another
program.

Figure : Relationship of java program with I/O devices


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

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

Input streams Reads


Source Program

a) Reading data into a program

Program Destination
Writes

Output streams

b) Writing data to a destination

Figure: Using input and 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.

Java Stream classes

Byte stream Character


classes stream classes

Write
Output Reader
Input Classes
Stream Classes
Stream

memory file pipe memory file pipe

Figure : Classification of java stream classes


3

BYTE STREAM CLASSES


Byte stream classes have been designed to provide functional features for creating
and manipulating streams and files for reading and writing bytes. Java provides two kinds
of byte stream classes: input stream classes and output stream classes.

Input stream classes


Input stream classes that are used to read 8-bit bytes include a super class known as
input stream and a number of subclasses for supporting various input-related functions.This
fig shows the class hierarchy of input stream classes.
The following are the methods provided by the InputStream class:

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

Output stream classes:


The several subclasses of the output stream can be used for performing the output
operations. The output stream includes methods are designed to perform the following
tasks:
• Writing bytes
• Closing streams
• Flushing streams

The following are the methods provided by the OutputStream class:

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 DataOutputStream, a counterpart of DataInputStream, implements the interface


DataOutput and, therefore, implements the following methods contained in DataOutput
interface.
a) writeShort() f) writeDouble()
b) writeInt() g) writeBytes()
c) writeLong() h) writeChar()
d) writeFloat() i) writeBoolean()
e) writeUTF()

Hierarchy of output stream classes


5

CHARACTER STREAM CLASSES


Character streams can be used to read and write 16-bit Unicode characters. Like
byte streams, there are two kinds of character stream classes, namely, reader stream
classes and writer stream classes.

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. These classes are functionally very
similar to the input stream classes.

Figure: Hierarchy of reader stream classes

Writer Stream classes


Like output stream classes, the writer stream classes are designed to perform all
output operations on files. Only difference is that while output stream classes are designed
to write bytes, the writer stream classes are designed to write characters.
The writer class is an abstract class which acts as a base class for all the other writer
stream classes
6

Hierarchy of writer stream classes

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.

Task character stream byte stream classes


classes
Performing input operations Reader Inputstream

Buffering input BufferedReader BufferedInputStream

Reading from an array CharArrayReader ByteArrayInputStream

Reading from files FileReader FileInputStream

Filtering the input FilterReader FilterInputStream

Pushing back characters/bytes PushBackReader PushbackInputStream

Reading from a string StringReader StringBufferInputStream

Reading primitive types (none) DataInputStream

Buffering output BufferedWriter BufferedOutputStream

Writing to an array CharArrayWriter ByteArrayOutputStream

Writing to a file FileWriter FileOutputStream


7

OTHER USEFUL I/O CLASSES


The java.io package supports many other classes for performing certain specialized
functions. They include among others:
• Random Access File
• Stream Tokenizer
The Random Access File enables us to read and write bytes, text and java data types
to any location in a file. This class extends object class and implements DataInput and
DataOutput interface as shown in below.
The class Stream Tokenizer, a subclass of object can be used for breaking up a
stream of text from an input text file into meaningful pieces called tokens. The behavior of
the Stream Tokenizer class is similar to that of the StringTokenizer class that breaks a string
into its component tokens. Object

DataInput DataOutput

RandomAccessFile

Figure : Implementation of the Random Access File

USING THE FILE CLASS


The java.io package includes a class known as the file class that provides that
support for creating files and directories. The class includes several constructors for
instantiating the File objects. This class also contains several methods for supporting the
operations such as
• Creating a file
• Opening a file
• Closing a file
• Deleting a file
• Getting the name of the file
• Getting the size of the file
• Checking the existence of a file
• Renaming a file
• Checking whether the file is writable
• Checking whether the file is readable
8

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.

I/O exception class Function


EOFException signals that an end of the file or end of stream has bee
reached unexpectedly during
input.
FileNotFoundException informs that a file could not be found
InterrupetedIOException warns that an I/O operations has been interrupted
IOException signals that an I/O exception of some sort has occurred

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.

Source or Characters Bytes


Destination Read Write Read Write
Memory CharArrayReade CharArrayWrite ByteArrayinputStream ByteArrayOutputStream
File FileReader FileWriter FilelnputStream FileOutputStream
Pipe PipedReader PipedWriter PipedinputStream PipedOutputStream

Figure: Common Stream Classes used for I/O Operations

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.

FileInputStream fis; // Declare a file Stream object


try
{
//Assign the filename to the file stream object
fis = new FileInputStream(“test.dat”);
……..
}
catch(IOException e)
…..
…..
The indirect approach uses a file object that has been initialized with the desired
filename.This is illustrated by the following code.
…………..
…………..
10

file inFile; //Declare a file object


InFile = new File(“test.dat”); //Assign the filename to
FileInputStream fis; // Declare a file Stream object
try
{
//Give the value of the file object
//to the file stream object
fis = new FileInputStream(inFile);
……..
}
catch (………)
……………
……………
The code above includes five tasks:
• Select a filename
• Declare a file object
• Give the selected name to the file object declared
• Declare a file stream object
• Connect the file to the file stream object

Both the approach are illustrated

Figure: Instantiating file stream objects

Example: Program to two file stream classes to copy the contents of a file named
“input.dat”into a file called “output.dat”.

//Copying character from one file into another


import java.io.*;
class Copy
11

{
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);

The following are the methods provided by the InputStream class:

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

The following are the methods provided by the OutputStream class:

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

//Copying character from one file into another


import java.io.*;
class Copy
{
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
13

{
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);

The following are the methods provided by the InputStream class:

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

The following are the methods provided by the OutputStream class:

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

//Program1 for writing bytes to a file:


import java.io.*;
class WriteBytes
{
public static void main (string args[])
{
//Declare and initialize a byte array
byte cities[]= {„D‟,‟E‟,‟L‟,‟H‟,‟I‟,‟\n‟};
15

//create an output file stream


FileOutputStream outfile=null;
try
{
//Connect the outfile stream to “city.txt”
Outfile=new FileOutputStream(“city.txt”);
//Write data to the stream
Outfile.write(cities);
Outfile.close();
}
catch (IOException ioe)
{
System.Out.println(ioe);
System.exit(-1);
}}}

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.

//Program2 for reading bytes from a file:

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

//Read and display data


while((b=infile.read())!=-1)
{
System.out.println((char)b);
}
infile.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}}}
Note that the program requires the filename to be given as a command line argument.
Program2 displays the following when we supply the filename "city.txt".
Prompt>java ReadOytes city.txt
DELHI
MADRAS
LONDON

HANDLING PRIMITIVE DATA TYPES

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

FileOutputStream fos = new FileOutputStream(outfile);


DataOutputStream dos = new DataOutputStream(fos);

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.

//Program for Reading and Writing primitive data:


import java.io.*;
class ReadWrite
{
public static void main (String args[]) throws IOException
{
file primitive=new File ("prim.dat");
FileOutputStream fos=new FileOutputStream (primitive);
DataOutputStream dos=new DataOutputStream (fos);
dos.writeInt(1999);
dos.writeDouble(375.85);
dos.writeBooloean(false);
dos.writeChar(„X‟);
dos.close();
fos.close();
FileInputStream fis=new FileInputStream (primitive);
DataInputStream dis=new DataInputStream (fis);
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
dis.close();
fis.close();
}
}

Output:
18

1999
375.85
false
X

RANDOM ACCESS FILES


The files that can be used either for "read only" or for "write only" operations. These
files are read or written only sequentially and, therefore, are known as sequential files.
The random access file class supported by the java.io package allows us to create files that
can be used for reading and writing data with random access. Such files are known as
random access files.
We can use one of the following two mode strings:
• "r" for reading only
• "rw" for both reading and writing
An existing file can be updated using the "rw" mode.
Random access files support a pointer known as file pointer that can be moved to
arbitrary positions in the file prior to reading or writing. The file pointer is moved using the
method seek () in the RandomAccessFile class. When the file is opened by the statement
file=new RandomAccessFile ("rand.dat", “rw”);
the file pointer is automatically positioned at the beginning of the file.

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.

The output on the screen would appear as follows:

X
555
3.1412
555
false

You might also like