Input Output Files
Input Output Files
Input Output Files
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
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
Mouse Printer
Java
Memory program Memory
Disk Disk
Input Output
Network Network
Copyright © 2009 by Royal Institute of Information Technology
Input stream
Reads
Source Program
Output stream
Writes
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
File
InputStream
FileInputStream SequenceInputStream
PipeInputStream ObjectInputStream
ByteArrayInputStream StringBufferInputStream
FilterInputStream
DataInputStream
DataInput
Copyright © 2009 by Royal Institute of Information Technology
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() Closes the input stream
(Continued)
Copyright © 2009 by Royal Institute of Information Technology
readShort()
readInt()
readLong()
Copyright © 2009 by Royal Institute of Information Technology
classes Object
OutputStream
FileOutputStream ObjectOutputStream
PipedOutputStream ByteArrayOutputStream
FilterOutputStream
BufferedOutputStream PushbackOutputStream
DataOutputStream
DataOutput
Copyright © 2009 by Royal Institute of Information Technology
Summary of OutputStream
Methods
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
Summary of OutputStream
Methods (Continued)
• The class DataOutputStream, a counterpart of
DataInputStream, implements the interface
DataOutput.
• Therefore, implements the following methods
contained in DataOutput interface.
writeShort()
writeInt()
writeLong()
Copyright © 2009 by Royal Institute of Information Technology
classes Object
Reader
BufferedReader StringReader
CharArrayReader PipeReader
InputStreamReader FilterReader
FileReader PushbackReader
Copyright © 2009 by Royal Institute of Information Technology
classes Object
Writer
BufferedWriter PrintWriter
CharArrayWriter StringWriter
FilterWriter PipeWriter
OutputStreamWriter
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
Interface Interface
DataInput DataOutput
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”
import java.io.*;
class CopyCharacters{
try{
int ch;
outs.write(ch);
}
Reading from and Writing to files
ins stream
input.dat
read()
inFile
Program
output.dat write()
import java.io.*;
class ReadBytes{
public static void main(String args[]){
FileInputStream infile = null;
int b;
try{
infile = new FileInputStream(args[0]);
while((b = infile.read()) != -1){
System.out.print((char) b);
}
infile.close();
}
catch(IOException ioe){
System.out.println(ioe);
}
}
}
Copying bytes from one file to
Copyright © 2009 by Royal Institute of Information Technology
another
import java.io.*;
class CopyBytes{
public static void main(String args[]){
FileInputStream infile = null;
FileOutputStream outfile = null;
byte byteRead;
try{
infile = new FileInputStream(“in.dat”);
outfile = new FileOutputStream (“out.dat”);
Program Continued
Copyright © 2009 by Royal Institute of Information Technology
catch(FileNotFoundException e){
System.out.println(“File not Found”);
}
catch(IOException e){
System.out.println(e.getMessage());
}
finally{
try{
infile.close();
Copyright © 2009 by Royal Institute of Information Technology
FilterInputStream DataInput
DataInputStream
Interface Class
DataOutput FilterOutputStream
DataOutputStream
Reading and Writing primitive
Copyright © 2009 by Royal Institute of Information Technology
data
import java.io.*;
class ReadWritePrimitive{
public static void main(String args[]) throws IOException{
File primitive = new File(“prim.dat”);
FileOutputStream fos = new FileOutputStream(primitive);
DataOutputStream dos = new DataOutputStream(fos);
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();
}
}
Using a Single file for storing and retrieving
Copyright © 2009 by Royal Institute of Information Technology
import java.io.*;
class ReadWriteIntegers{
public static void main(String args[]){
// Declare data streams
DataInputStream dis = null;
DataOutputStream dos = null;
// Construct a file
File inFile = new File(“rand.dat”);
// Writing integers to rand.dat file
try{
dos = new DataOutputStream(new
Program (Continued) Copyright © 2009 by Royal Institute of Information Technology
catch(IOException ioe){
System.out.println(ioe.getMessage());
finally{
try{
dos.close();
catch(IOException ioe) { }
try{
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
System.out
Program of Concatenation and
Copyright © 2009 by Royal Institute of Information Technology
Buffering
import java.io.*;
class SequenceBuffer{
public static void main(String args[]) throws IOException{
//Declare file streams
FileInputSteram file1 = null;
FileInputStream file2 = null;
//Declare file3 to store combined files
SequenceInputStream file3 = null;
file1 = new FileInputStream(“text1.dat”);
file2 = new FileInputStream(“text2.dat”);
Program (Continued)
Copyright © 2009 by Royal Institute of Information Technology
import java.io.*;
class RandomIO{
public static void main(String args[]) throws IOException{
RandomAccessFile file = null;
try{
file = new RandomAccessFile(“rand.dat”, “rw”);
file.WriteChar(‘X’);
file.writeInt(555);
file.writeDouble(3.1412);
file.seek(0); //Go to the beginning
System.out.println(file.readChar());
Program (Continued)
Copyright © 2009 by Royal Institute of Information Technology
import java.util.*;
import java.io.*;
class Inventory{
static DataInputStream din = new DataInputStream(System.in);
static StringTokenizer st;
public static void main(String args[]) throws IOException{
DataOutputStream dos = new DataOutputStream(new FileOutputStream(“invent.dat”));
System.out.println(“Enter code number”);
st = new StringTokenizer(din readLine());
int code = Integer.parseInt(st.nextToken());
System.out.println(“Enter number of items”);
st = new StringTokenizer(din.readLine());
int items = Integer.parseInt(st.nextToken());
(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
import java.awt.*;
DataOutputStream dos;
public StudentFile(){
resize(400, 200);
(Continued)
Program (Continued) Copyright © 2009 by Royal Institute of Information Technology
add(numLabel);
add(number);
add(nameLabel);
add(name);
add(markLabel);
add(marks);
add(enter);
add(done);
show();
try{
catch(IOException e){
System.err.println(e.toString());
System.exit(1);
int num;
Double d;
(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) { }
number.setText(“ ”);
name.setText(“ ”);
marks.setText(“ ”);
addRecord();
try{
dos.flush();
dos.close();
catch(IOException e) { }
(Continued)
Program (Continued) Copyright © 2009 by Royal Institute of Information Technology
if(event.arg.equals(“ENTER”)){
addRecord();
return true;
if(event.arg.equals(“DONE”)){
cleanup();
System.exit(0);
return true;
return super.handleEvent(event);
student.setup();
}
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