Managing Input / Output Files in Java
Managing Input / Output Files in Java
Introduction
• A file is a collection of related records placed in
a particular area on the disk
• A record is composed of several fields
• A field is a group of characters.
• Characters in java are Unicode characters
composed of two bytes.
• Each Byte containing eight binary digits, 1 or 0
• Storing and Managing data using files is known
as file processing which includes tasks such as
creating, updating files and manipulation of data
Copyright © 2009 by Royal Institute of Information Technology
Concept of Streams
• 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.
• Stream has a source (of data) and a destination
(for that data) may be physical devices or
programs or other streams in the program
Copyright © 2009 by Royal Institute of Information Technology
Keyboard Screen
Keyboard Screen
Mouse Printer
Mouse Printer
Java
Memory program Memory
Memory Memory
Disk Disk
Disk Disk
Input Output
Network Network
Network Network
Copyright © 2009 by Royal Institute of Information Technology
Input stream
Reads
Source Program
Source Program
Output stream
Writes
Program Destination
Program Destination
Stream Classes
• The java.io package contains a large number of
stream classes that provide capabilities for
processing all type of data.
• These classes may be categorized into two
groups
▫ Byte stream classes that provide support for
handling I/O operations on bytes.
▫ Character stream classes that provide
support for managing I/O operations on
characters.
Copyright © 2009 by Royal Institute of Information Technology
InputStream
InputStream
FileInputStream SequenceInputStream
FileInputStream SequenceInputStream
PipeInputStream ObjectInputStream
PipeInputStream ObjectInputStream
ByteArrayInputStream StringBufferInputStream
FilterInputStream
FilterInputStream
DataInputStream
DataInputStream
DataInput
DataInput
Copyright © 2009 by Royal Institute of Information Technology
(Continued)
Copyright © 2009 by Royal Institute of Information Technology
OutputStream
OutputStream
FileOutputStream ObjectOutputStream
FileOutputStream ObjectOutputStream
PipedOutputStream ByteArrayOutputStream
FilterOutputStream
FilterOutputStream
BufferedOutputStream PushbackOutputStream
DataOutputStream
DataOutputStream
DataOutput
DataOutput
Copyright © 2009 by Royal Institute of Information Technology
Method Description
write() Writes a byte from the input stream
write(byte b[ ]) Writes all bytes in the array of b to the output
stream
write(byte b[ ], int n, int m) Writes m bytes into b starting from nth byte
close() Close the output Stream
flush() Flushes the Output Stream
(Continued)
Copyright © 2009 by Royal Institute of Information Technology
▫ writeShort() ▫ writeDouble()
▫ writeInt() ▫ writeBytes()
▫ writeLong() ▫ writeChar()
▫ writeFloat() ▫ writeBoolean()
▫ writeUTF()
Copyright © 2009 by Royal Institute of Information Technology
Reader
Reader
BufferedReader StringReader
BufferedReader StringReader
CharArrayReader PipeReader
PipeReader
InputStreamReader FilterReader
FilterReader
FileReader PushbackReader
FileReader PushbackReader
Copyright © 2009 by Royal Institute of Information Technology
Writer
Writer
BufferedWriter PrintWriter
BufferedWriter PrintWriter
CharArrayWriter StringWriter
CharArrayWriter StringWriter
FilterWriter PipeWriter
FilterWriter PipeWriter
OutputStreamWriter
OutputStreamWriter
FileWriter
FileWriter
Copyright © 2009 by Royal Institute of Information Technology
RandomAccessFile
• The RandomAccessFile 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.
• This forces the RandomAccessFile to
implement the methods described in both these
interfaces
Copyright © 2009 by Royal Institute of Information Technology
Implementation of the
RandomAccessFile
Object
Object
Interface Interface
Interface Interface
DataInput DataOutput
DataInput DataOutput
RandomAccessFile
RandomAccessFile
Copyright © 2009 by Royal Institute of Information Technology
StreamTokenizer
• The class StreamTokenizer, 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 StringTokenizer class is
similar to that of the StringTokenizer class (of
java.util package) that breaks into its
component tokens.
Copyright © 2009 by Royal Institute of Information Technology
fis “test.dat”
fis “test.dat”
Stream object Filename
Stream object Filename
import java.io.*;
class CopyCharacters{
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);
outs = new FileWriter(outFile);
int ch;
while( (ch = ins.read()) != -1){
outs.write(ch);
}
}
catch(IOException e){
System.out.println(e);
System.exit(-1);
}
finally{
try{
ins.close();
outs.close();
}
catch(IOException e) { }
}
}
}
Reading from and Writing to files
ins stream
ins stream
input.dat
input.dat
read()
inFile read()
inFile
Program
Program
output.dat write()
output.dat write()
Program Continued
catch(FileNotFoundException e){
System.out.println(“File not Found”);
}
catch(IOException e){
System.out.println(e.getMessage());
}
finally{
try{
infile.close();
outfile.close();
}
catch(IOException e){ }
}
}
}
Copyright © 2009 by Royal Institute of Information Technology
FilterInputStream DataInput
DataInput
DataInputStream
Interface Class
DataOutput FilterOutputStream
DataOutput
DataOutputStream
Copyright © 2009 by Royal Institute of Information Technology
Program (Continued)
//Read data from to the “prim.dat” file
FileInputStream fis = new FileInputStram(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();
}
}
Copyright © 2009 by Royal Institute of Information Technology
catch(IOException ioe){
System.out.println(ioe.getMessage());
}
finally{
try{
dos.close();
}
catch(IOException ioe) { }
}
try{
dis = new DataInputStream(new FileInputStream(inFile));
for(int i=0; i<20; i++){
int n = dis.readInt();
System.out.print(n + “ ”);
}
catch(IOException ioe){
System.out.println(ioe.getMessage());
}
finally{
try{
dis.close();
}
catch(IOException ioe) { }
}
}
}
Copyright © 2009 by Royal Institute of Information Technology
Program
outBuffer write()
Screen
Screen
System.out
Copyright © 2009 by Royal Institute of Information Technology
Program (Continued)
BufferedInputStream inBuffer = new
BufferedInputStream(file3);
BufferedOutputStream outBuffer = new
BufferedOutputStream(System.out);
//Read and Write till the end of buffers
int ch;
while ((ch = inBuffer.read()) != -1){
outBuffer.write((char) ch);
}
inBuffer.close();
outBuffer.close();
file1.close();
file2.close();
}
}
Copyright © 2009 by Royal Institute of Information Technology
(Continued)
Copyright © 2009 by Royal Institute of Information Technology
Program (Continued)
file.seek(2) // Go to the second item
System.out.println(file.readInt());
// Go to the end and append false to the file
file.seek(file.length());
file.writeBoolean(false);
file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
Copyright © 2009 by Royal Institute of Information Technology
(Continued)
Program (Continued) Copyright © 2009 by Royal Institute of Information Technology
System.out.println(“Enter cost”);
st = new StringTokenizer(din.readLine());
double cost = new Double(st.nextToken()).doubleValue();
dos.writeInt(code);
dos.writeInt(items);
dos.writeDouble(cost);
dos.close();
DataInputStream dis = new DataInputStream(new
FileInputStream(“invent.dat”));
int codeNumber = dis.readInt();
int totalItems = dis.readInt();
double itemCost = dis.readDouble();
double totalCost = totalItems * itemCost;
dis.close();
System.out.println();
System.out.println(“Code Number : ”+ codeNumber);
System.out.println(“Item Cost : ”+ itemCost);
System.out.println(“Total Items :”+ totalItems);
System.out.println(“Total Cost :”+ totalCost);
}
}
Copyright © 2009 by Royal Institute of Information Technology
(Continued)
Program (Continued) Copyright © 2009 by Royal Institute of Information Technology
try{
dos.writeInt(num);
dos.writeUTF(name.getText());
d = new Double(marks.getText());
dos.writeDouble(d.doubleValue());
}
catch(IOException e) { }
//clear the text fields
number.setText(“ ”);
name.setText(“ ”);
marks.setText(“ ”);
}
//Adding the record and clearing the
public void cleanup(){
if(! number.getText().equals(“ “)){
addRecord();
}
try{
dos.flush();
dos.close();
}
catch(IOException e) { }
}
(Continued)
Program (Continued) Copyright © 2009 by Royal Institute of Information Technology
Object Streams
• It is also possible to perform input and output
operations on objects using the object streams.
• The object streams are created using
ObjectInputStream and
ObjectOutputStream classes.
• We may declare records as objects and use the
object classes to write and read these objects
from files.
• This process is known as object serialization.
Copyright © 2009 by Royal Institute of Information Technology
Piped Streams
• Piped streams provide functionality for threads
to communicate and exchange data between
them.
• The write thread sends data to the read thread
through a pipeline that connects an object of
PipedInputStream to an object of
PipedOutputStream.
• The objects inputPipe and outputPipe are
connected using the connect() method.
Copyright © 2009 by Royal Institute of Information Technology
inputPipe outputPipe
Pushback Streams
• The pushback streams created by the classes
PushbackInputStream and
PushbackReader can be used to push a single
byte or a character back into the input stream so
that it can be reread.
• When a character indicating a new input token is
read, it is pushed back into the input stream
until the current input token is processed.
Copyright © 2009 by Royal Institute of Information Technology
Filtered Streams
• Java supports two abstract classes, namely,
FilterInputStream and FilterOutputStream
that provides the basic capability to create input and
output streams for filtering 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
Input Output
stream stream
Filter 1 Filter 2 Filter 3
Filter 1 Filter 2 Filter 3