UNIT-V
Managing Input/Output Files in JAVA
Introduction
Variables and arrays for storing data inside the programs. limitations:
The data is lost when variable goes out of scope or when the program terminates.
That is data stored is released when program terminates.
It is difficult to handle large volumes of data.
Solution - by storing data on secondary storage devices such as floppy or hard disks.
The data is stored in these devices using the concept of Files and such data is often called
persistent data.
File Processing
Storing and manipulating data using files is known as file processing.
Reading/Writing of data in a file can be performed at the level of bytes, characters, or fields
depending on application requirements.
Java also provides capabilities to read and write class objects directly.
The process of reading and writing objects is called object serialisation.
I/O and Data Movement
The flow of data into a program (input) may come from different devices such as keyboard,
mouse, memory, disk, network, or another program.
The flow of data out of a program (output) may go to the screen, printer, memory, disk,
network, another program.
Both input and output share a certain common property such as unidirectional movement of
data
a sequence of bytes and characters and support to the sequential access to the data.
Streams
Java Uses the concept of Streams to represent the ordered sequence of data, a common
characteristic shared by all I/O devices.
Streams presents a uniform, easy to use, object oriented interface between the program and I/O
devices.
A stream in Java is a path along which data flows (like a river or pipe along which water flows).
Stream Types
The concepts of sending data from one stream to another (like a pipe feeding into another pipe)
has made streams powerful tool for file processing.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data
from a source (keyboard, file, etc.)
it acts as a buffer between the data source and destination
Connecting streams can also act as filters.
writes
Streams are classified into two basic types:
Input Steam
Output Stream
1
Input stream: a stream that provides input to a program
[Link] is an input stream
Output stream: a stream that accepts output from a program
[Link] is an output stream
A stream connects a program to an I/O object
[Link] connects a program to the screen
[Link] connects a program to the keyboard
I/O: General Scheme
In General:
Reading (writing):
open an input (output) stream
while there is more information
read(write) next data from the stream
close the stream.
In JAVA:
Create a stream object and associate it with a disk-file
– Give the stream object the desired functionality
while there is more information
read(write) next data from(to) the stream
close the stream.
Java Stream Classes
Input/Output related classes are defined in [Link] package.
Input/Output in Java is defined in terms of streams.
A stream is a sequence of data, of no particular length.
Java classes can be categorised into two groups based on the data type one which they
operate:
Byte streams
Operations on Bytes
Character Streams
Operations on Characters
Byte-based streams – stores data in binary format
Binary files – created from byte-based streams, read by a program that converts data to
human-readable format
Character-based streams – stores data as a sequence of characters
Text files – created from character-based streams, can be read by text editors
Streams
Byte Streams Character streams
Operated on 8 bit (1 byte) data. Operates on 16-bit (2 byte) unicode characters.
Input streams/Output streams Readers/ Writers
Byte Stream
Byte streams are defined using two class hierarchies, InputStream and OutputStream
Two of the most important are read() and write().
Byte Input Streams - Hierarchy of Input Stream Classes
2
InputStream
the abstract class that describes stream input.
To use it, we must define
InputStream is = new BufferedInputStream([Link]);
[Link]();
The InputStream class defines methods for performing input functions such as
Reading Bytes
Closing Streams
Marking positions in Streams
Skipping ahead in a stream
Finding the number of bytes in a stream.
Byte Input Streams – operations
public abstract int read() Reads a byte and returns as a integer 0-255
public int read(byte[] buf, int offset, int Reads and stores the bytes in buf starting at offset.
count) Count is the maximum read.
public int read(byte[] buf) Same as previous offset=0 and length=[Link]()
public long skip(long count) Skips count bytes.
public int available() Returns the number of bytes that can be read.
public void close() Closes stream
The class DataInputStream extends FilterInputStream and implements the interface DataInput.
Example
Output Streams Classes
Output Streams includes methods
Writing Bytes
Closing Streams
Flushing Streams
Byte Streams - Hierarchy of Output Stream Classes
Byte Output Streams – operations
public abstract void write(int b) Write b as bytes.
public void write(byte[] buf, int offset, int count) Write count bytes starting from offset in buf.
public void write(byte[] buf) Same as previous offset=0 and count =
[Link]()
3
public void flush() Flushes the stream.
public void close() Closes stream
Byte Output Stream – example
Read from standard in and write to standard out
import [Link].*;
class ReadWrite {
public static void main(string[] args)
throws IOException
{
int b;
while (( b = [Link]()) != -1)
{
[Link](b);
}
}
Character Stream Classes
Character streams are defined by using two class hierarchies.
The two abstract classes are
Reader Stream Classes and
Writer Stream Classes
These abstract classes handle Unicode character streams.
Reader Class Hierarchy
Writer
This is an abstract class that describes character stream output.
The format is:
Writer w = new OutputStreamer([Link]);
[Link](“This is the output”); //prepares to send
[Link](); // send it out
Writer Class Hierarchy
Example
4
Using Streams
Table 16.3
List of Tasks and Classes implementing them
Other Useful I/O Classes
Specialized functions
Random Access File
Stream Tokenizer
Implementation of the RandomAccess File
Using the File Class
Operations on Files
Creating a file
Opening a file
Closing a file
Deleting a file
Getting the name of a file
Getting the size of a file
Checking the existence of a file
Renaming a file
Checking whether the file is writable
Checking whether the file is readable
Input/Output Exceptions
When creating files and performing I/O operations on them, the systems generates errors.
The basic I/O related exception classes,
EOFException – signals that end of the file is reached unexpectedly during input.
FileNotFoundException – file could not be opened
InterruptedIOException – I/O operations have been interrupted
IOException – signals that I/O exception of some sort has occurred – very general I/O
exception.
Syntax
Each I/O statement or a group of I/O statements much have an exception handler around
it/them as follows:
try {
…// I/O statements – open file, read, etc.
}
catch(IOException e) // or specific type exception
{
…//message output statements
}
Creation of Files
A filename is a unique string of characters that helps to identify file on the disk.
2 parts
1. Primary name
2. Optional period with extension
Examples: [Link] , [Link]
A file stream can be defined using the classes of
Reader/InputStream for reading data
Writer/OutputStream for writing data
5
Creation of Files
There are 2 ways of initialising file stream objects:
Passing file name (directly) to the stream constructor
Passing File Object (indirectly) :
Manipulation operations are same once the file is opened.
Passing file name (directly)
FileInputStream fis; // Declare a file stream object
try
{
//Assign the filename to the file stream object
fis = new FileInputStream(“[Link]”);
....
}
Passing File Object (indirectly)
File inFIle;
InFile = new File(“[Link]”);
FileInputStream fis;
Try
{
//Give the value of the file object to the file stream object
fis = new FileInputStream(inFile);
…
}
Reading/ Writing Characters
Example Program 16.1
Fig 16.12
Reading/ Writing Bytes
Example Program 16.2 & 16.3
Five Tasks:
1. Select a Filename
2. Declare a file object
3. Give the selected name to the file object declared
4. Declare a file stream object
5. Connect the file to the file stream object.
Fig 16.11 Instantiating File Stream Objects
Handling Primitive Data Types
Basic IO streams provide read/write methods that can only be used for reading/ writing bytes or
characters.
To read/write primitive data type – Integers, Doubles
Filter Classes
Wrappers on existing input and output streams to filter data in the original
stream.
Two Filter Classes used for creating “Data Streams “ for handling Primitive types are,
DataInputStream and DataOutputStream
Hierarchy of Data Stream Classes
6
Class DataOutput
Interface
FilterOutputStream
DataOutputStream
A Data stream for Input can be created as,
FileInputStream fis = new FileInputStream(infile);
DataInputStream dis = new DataInputStream(fis);
A Data stream for Output can be created as,
FileOutputStream fos = new FileOutputStream(infile);
DataInputStream dos = new DataInputStream(fis);
Example Program : 16.5 R/W Primitive Data
Data Input Stream Creation
Create Input File Stream:
FileInputStream fis = new FileInputStream(“InFile”);
Create Input Data Stream:
DataInputStream dis = new DataInputStream( fis );
The above statements wrap data input stream (dis) on file input stream (fis) and use it as a
“filter”.
Methods Supported:
readBoolean(), readByte(), readChar(), readShort(), readInt(), readLong(), readFloat(), readDouble()
They read data stored in file in binary format.
Data Output Stream Creation
Create Output File Stream:
FileOutputStream fos = new FileOutputStream(“OutFile”);
Create Output Data Stream:
DataOutputStream dos = new DataOutputStream( fos );
The above statements wrap data output stream (dos) on file output stream (fos) and use it as a
“filter”.
Methods Supported:
writeBoolean(), writeByte(), writeChar(), writeShort(), writeInt(), writeLong(), writeFloat(),
writeDouble()
They write data to file in binary format.
Data Streams Flow via Filter
Write primitive data to the file using a filter.
dos fos
filter binary stream
Program mydata
Read primitive data from the file using a filter.
fis dis
mydata binary stream filter
Program Screen
7
Random Access Files
sequential files –used for storing data and accessed (read/write) them in sequence.
In most real world applications, it is necessary to access data in non-sequential order (e.g,
banking system) and append new data or update existing data.
Java .io package supports RandomAccessFile class that allow us to create files that can be used
for reading and/or writing with random access.
The file can be open either in
read mode (“r”) or
read-write mode (“rw”)
myFileHandleName = new RandomAccessFile (“filename”, “mode”);
The file pointer can be set to any to any location (measured in bytes) using seek() method prior
to reading or writing.
Example Program:
Prgm 12: APPENDING AN EXISTING FILE
All Java I/O classes are designed to operate with Exceptions.
User Exceptions and your own handler with files to manger runtime errors.
Subclasses FileReader / FileWriter support characters-based File I/O.
FileInputStream and FileOutputStream classes support bytes-based File I/O.
Buffered read/write operations support efficient I/O.
DataInputStream and DataOutputStream classes support rich I/O functionality.
RandomAccessFile supports access to any data items in files in any order.