input output files
TRANSCRIPT
-
8/9/2019 Input Output Files
1/63
Managing Input /
Output Files in JavaCopyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
2/63
Introduction
Afile is a collection of related records placed ina particular area on the disk
Arecordis composed of several fields
Afieldis a group of characters.
Characters in java are Unicode characters
composed of two bytes. EachByte containing eight binary digits, 1 or 0
Storing and Managing data using files is knownasfile processingwhich includes tasks such as
creating, updating files and manipulation of data
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
3/63
Concept of Streams Java uses the concept of streams to represent the
ordered sequence of data
Acommon characteristic shared by all the Input /Output devices.
Astream 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 orprograms or other streams in the program
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
4/63
Relationship of Java program withI/O devices
Copyright 2009 by Royal Institute of Information Technology
Keyboard
Mouse
Memory
Disk
Network
Screen
Printer
Memory
Disk
Network
Javaprogram
Sources Destinations
Input Output
-
8/9/2019 Input Output Files
5/63
Using input and Output Streams Java streams are classified into two basic types,
namely, input stream and output stream
Copyright 2009 by Royal Institute of Information Technology
Source Program
Input streamReads
(a) Reading data into a program
DestinationProgram
(b) Writing data into a destination
WritesOutput stream
-
8/9/2019 Input Output Files
6/63
Stream Classes Thejava.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 oncharacters.
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
7/63
Classification of Java stream classesCopyright 2009 by Royal Institute of Information Technology
JavaStream Classes
Character StreamClasses
Byte StreamClasses
Input Stream
Classes
Output Stream
Classes
Reader
Classes
riter
Classes
File PipeMemory Memory
File Pipe
-
8/9/2019 Input Output Files
8/63
Byte Stream Classes
Byte stream classes have been designed to
provide functional features for creating andmanipulating streams and files for reading andwriting bytes.
Java provides two kinds of byte stream classes :
input stream classes output stream classes
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
9/63
Input Stream Classes
Input stream classes that are used to read 8-bit
bytes include a super class known asInputStream.
The super classInputStream is an abstractclass, and, therefore we cannot create instances
of this class. Rather, we must use the subclasses that inherits
from this class.
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
10/63
Hierarchy of input stream classesCopyright 2009 by Royal Institute of Information Technology
File
InputStream
FilterInputStream
DataInputStream
DataInput
FileInputStream SequenceInputStream
PipeInputStream ObjectInputStream
ByteArrayInputStream StringBufferInputStream
-
8/9/2019 Input Output Files
11/63
Summary of InputStream Methods
Method Description
read() Reads a byte from the input streamread(byte b[ ]) Reads an array of bytes into b
read(byte b[ ], int n, int m) Reads m bytes into b starting from nthbyte
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
Copyright 2009 by Royal Institute of Information Technology
(Continued)
-
8/9/2019 Input Output Files
12/63
Summary of InputStream Methods(Continued)
readShort() readInt() readLong() readFloat()
readUTF()
readDouble() readLine() readChar() readBoolean()
Copyright 2009 by Royal Institute of Information Technology
The classDataInputStream extendsFilterInputStream and Implements the
interfaceDataInput. Therefore, theDataInputStream class
implements the methods described inDataInput
DataInputinterface contains
-
8/9/2019 Input Output Files
13/63
Output Stream Classes
Output stream classes are derived from the base
class OutputStream LikeInputStream, the OutputStream is an
abstract class and therefore we cannotinstantiate it.
The several subclasses of the OutputStreamcan be used for performing the outputoperations.
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
14/63
Hierarchy of output stream classesCopyright 2009 by Royal Institute of Information Technology
OutputStream
FilterOutputStream
DataOutputStream
DataOutput
FileOutputStream ObjectOutputStream
ByteArrayOutputStream
Object
PipedOutputStream
PushbackOutputStreamBufferedOutputStream
-
8/9/2019 Input Output Files
15/63
Summary of OutputStream Methods
Method Description
write() rites a byte from the input streamwrite(byte b[ ]) rites all bytes in the array of b to the output
stream
write(byte b[ ], int n, int m) rites m bytes into b starting from nthbyte
close() Close the output Stream
flush() Flushes the Output Stream
Copyright 2009 by Royal Institute of Information Technology
(Continued)
-
8/9/2019 Input Output Files
16/63
Summary of OutputStream Methods(Continued)
writeShort() writeInt() writeLong() writeFloat()
writeUTF
()
writeDouble() writeBytes() writeChar() writeBoolean()
Copyright 2009 by Royal Institute of Information Technology
The classDataOutputStream, a counterpart ofDataInputStream, implements the interface
DataOutput.
Therefore, implements the following methodscontained inDataOutputinterface.
-
8/9/2019 Input Output Files
17/63
Character Stream Classes
Character stream classes were not a part of the
language when it was released in 1995. They were added when the version 1.1 was
announced.
Character streams can be used to read and write
16-bit Unicode characters. There are two kind of character stream classes
Reader Stream Classes
Writer Stream Classes
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
18/63
Reader Stream Classes
Reader stream classes are designed to readcharacter from the files.
Readerclass is the base class for all otherclasses in this group.
TheReaderclass contains methods that areidentical to those available in theInputStreamclass, except Reader is designed to handlecharacters.
Readerclass can perform all the functions
implemented by the input stream classes
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
19/63
Hierarchy of reader stream classesCopyright 2009 by Royal Institute of Information Technology
Reader
BufferedReader
PipeReader
StringReader
Object
InputStreamReader
CharArrayReader
FilterReader
FileReader PushbackReader
-
8/9/2019 Input Output Files
20/63
Writer 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 writerstream classes are designed to write characters
The Writerclass is an abstract class which actsas a base class for all other writer stream classes.
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
21/63
Hierarchy of writer stream classesCopyright 2009 by Royal Institute of Information Technology
Writer
Object
Buffered riter
CharArray riter
Filter riter
Print riter
String riter
Pipe riter
OutputStreamWriter
FileWriter
-
8/9/2019 Input Output Files
22/63
Other Useful I/O Classes
The java.io package supports many other classes
for performing certain specialized functions. RandomAccessFile
StreamTokenizer
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
23/63
RandomAccessFile
TheRandomAccessFile enables us to read
and write bytes, text andJ
ava data types to anylocation in a file.
This class extends objectclass and implementsDataInputandDataOutputinterface.
This forces theRandomAccessFile toimplement the methods described in both theseinterfaces
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
24/63
Implementation of theRandomAccessFile
Copyright 2009 by Royal Institute of Information Technology
Object
RandomAccessFile
DataOutputDataInput
InterfaceInterface
-
8/9/2019 Input Output Files
25/63
StreamTokenizer
The classStreamTokenizer, a subclass of
objectcan be used for breaking up a stream oftext from an input text file into meaningfulpieces called tokens.
The behavior of theStringTokenizerclass is
similar to that of theStringTokenizerclass (ofjava.utilpackage) that breaks into itscomponent tokens.
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
26/63
Using the File Class Thejava.io package includes a class known as theFile class
that provides support for creating files and directories.
The class also contains several methods. 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
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
27/63
Important I/O Exception Classes
I/O Exception class Function
EOFExceptionS
ignals that an end of the file or end of streamhas been reached unexpectedly during input
FileNotFoundException Informs that a file could not be found
InterruptedIOException arns that an I/O operations has beeninterrupted
IOException Signals that an I/O exception of some sort hasoccurred
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
28/63
Common Stream Classes used for I/OOperations
Copyright 2009 by Royal Institute of Information Technology
Source Characters BytesRead Write Read Write
Memory CharArrayReader CharArrayReader ByteArrayInputStream ByteArrayOutputStream
File FileReader File
riter FileInputStream FileOutputStream
Pipe PipedReader Piped
riter PipedInputStream PipedOutputStream
-
8/9/2019 Input Output Files
29/63
Instantiating file stream objects
Copyright 2009 by Royal Institute of Information Technology
fis test.dat
inFilefis test.dat
Stream object Filename
Stream object File object Filename
-
8/9/2019 Input Output Files
30/63
Copying Charactersimport java.io.*;
class CopyCharacters{public static void main(String args[ ]){
File inFile = newFile(input.dat);
File outFile = newFile(output.dat);
FileReaderins = null;
File
riter outs = null;
try{
ins = newFileReader(inFile);
outs = newFile
riter(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) { }
}
}}
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
31/63
Reading from and Writing to files
input.dat
output.dat
inFile
outFile
Program
outs stream
ins stream
read()
write()
-
8/9/2019 Input Output Files
32/63
Writing bytes to a fileimport java.io.*;class riteBytes{
public static void main(String args[]){byte cities[] = {D, E, L, H, I, \n, M, A, D, R, A,S, \n, L, O, N, D, O, N, \n };
FileOutputStream outfile = null;try{
outfile = newFileOutputStream (city.txt);outfile.write(cities);outfile.close();
}catch(IOException ioe){System.out.println(ioe);System.out.println(-1);
}}
}
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
33/63
Reading Bytes from a fileimport java.io.*;class ReadBytes{
public static void main(String args[]){FileInputStream infile = null;int b;try{
infile = newFileInputStream(args[0]);while((b = infile.read()) != -1){
System.out.print((char) b);}
infile.close();}catch(IOException ioe){
System.out.println(ioe);}
}
}
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
34/63
Copying bytes from one file to anotherimport java.io.*;class CopyBytes{
public static void main(String args[]){FileInputStream infile = null;FileOutputStream outfile = null;
byte byteRead;try{
infile = newFileInputStream(in.dat);outfile = newFileOutputStream (out.dat);do{
byteRead = (byte) infile.read();outfile.write(byteRead);
}while (byteRead != -1);
}
(Continued)
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
35/63
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
-
8/9/2019 Input Output Files
36/63
Handling Primitive Data Types
To read/write the primitive data types, we canusefilter classes as wrappers on existing inputand output streams to filter data in the originalstream.
The two filter classes used for creating data
streams for handling primitive types areDataInputStream andDataOutputStream.
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
37/63
Hierarchy of Data Stream classes
Copyright 2009 by Royal Institute of Information Technology
DataInput
DataOutput
FilterInputStream
DataInputStream
DataOutputStream
FilterOutputStream
Class
ClassInterface
Interface
-
8/9/2019 Input Output Files
38/63
Reading and Writing primitive data
import java.io.*;
class Read ritePrimitive{
public static void main(String args[]) throws IOException{
File primitive = newFile(prim.dat);
FileOutputStream fos = newFileOutputStream(primitive);
DataOutputStream dos = new DataOutputStream(fos);
//Write primitive data to the prim.dat file
dos.writeInt(1999);dos.writeDouble(375.85);
dos.writeChar(X);
dos.close();
fos.close(); (Continued)
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
39/63
Program (Continued)//Read data from to the prim.dat file
FileInputStream fis = newFileInputStram(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
-
8/9/2019 Input Output Files
40/63
Using a Single file for storing and retrievingCopyright 2009 by Royal Institute of Information Technology
import java.io.*;class Read riteIntegers{
public static void main(String args[]){// Declare data streamsDataInputStream dis = null;
DataOutputStream dos = null;// Construct a file
File inFile = newFile(rand.dat);
// Writing integers to rand.dat filetry{
dos = new DataOutputStream(newFileOutputStream(inFile));
for(int i = 0; i
-
8/9/2019 Input Output Files
41/63
Program (Continued)catch(IOException ioe){
System.out.println(ioe.getMessage());}finally{
try{dos.close();
}catch(IOException ioe) { }
}
try{dis = new DataInputStream(newFileInputStream(inFile));for(int i=0; i
-
8/9/2019 Input Output Files
42/63
Concatenating and Buffering Files Combine two or more input streams (files) into a
single input stream(file). This process is known as
concatenation of file. It is achieved using theSequenceInputStream
class. Creation of buffers to store temporarily data that is
read from or written to a stream. This process is
known as buffered i/o operation. Buffers can be created using the
BufferedInputStream andBufferedOutputStream classes.
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
43/63
IIIustration of concatenation andBuffering
Copyright 2009 by Royal Institute of Information Technology
file 1
file 2 file3
file1 + file2
inBuffer
Program
Screen
outBuffer
System.out
read()
write()
-
8/9/2019 Input Output Files
44/63
Program ofConcatenation and BufferingCopyright 2009 by Royal Institute of Information Technology
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 = newFileInputStream(text1.dat);file2 = newFileInputStream(text2.dat);
//Concatenate file1 and file2 into file3
file3 = newSequenceInputStream (file1, file2);
(Continued)
-
8/9/2019 Input Output Files
45/63
Program (Continued)BufferedInputStream inBuffer = new
BufferedInputStream(file3);BufferedOutputStream outBuffer = new
BufferedOutputStream(System.out);//Read and Write till the end ofbuffersint 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
-
8/9/2019 Input Output Files
46/63
Random Access Files
RandomAccessFile class supported by thejava.iopackage allows us to create files that can be used forreading and writing data with random access.
Afile can be created and opened for random access by
giving a mode string as a parameter to the constructerwhen we open file.
r for reading only
rw for both reading and writing
Random access files support a pointer known asfilepointerthat can be moved to arbitrary positions in thefile prior to reading or writing.
The file pointer is moved using the method seek() in theRandomAccessFile class.
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
47/63
Reading/Writing using a random access fileCopyright 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. riteChar(X);file.writeInt(555);file.writeDouble(3.1412);
file.seek(0); //Go to the beginningSystem.out.println(file.readChar());System.out.println(file.readInt());System.out.println(file.readDouble());
(Continued)
-
8/9/2019 Input Output Files
48/63
Program (Continued)Copyright 2009 by Royal Institute of Information Technology
file.seek(2) // Go to the second itemSystem.out.println(file.readInt());// Go to the end and append false to the filefile.seek(file.length());
file.writeBoolean(false);file.seek(4);System.out.println(file.readBoolean());file.close();
}catch(IOException e){
System.out.println(e);}
}
}
-
8/9/2019 Input Output Files
49/63
Appending to an existing fileCopyright 2009 by Royal Institute of Information Technology
import java.io.*;class RandomAccess{
static public void main(String args[]){RandomAccessFile rFile;
try{ rFile = new RandomAccessFile(city.txt , rw);rFile.seek(rFile.length());rFile.writeBytes(MUMBAI/n);rFile.close();
}catch(IOException ioe){
System.out.println(ioe);}
}
}
-
8/9/2019 Input Output Files
50/63
Interactive input and outputCopyright 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 = newStringTokenizer(din readLine());
int code = Integer.parseInt(st.nextToken());System.out.println(Enter number of items);st = newStringTokenizer(din.readLine());int items = Integer.parseInt(st.nextToken());
(Continued)
-
8/9/2019 Input Output Files
51/63
Program (Continued) Copyright 2009 by Royal Institute of Information TechnologySystem.out.println(Enter cost);
st = newStringTokenizer(din.readLine());double cost = new Double(st.nextToken()).doubleValue();dos.writeInt(code);dos.writeInt(items);dos.writeDouble(cost);dos.close();
DataInputS
tream dis = new DataInputS
tream(newFileInputStream(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);
}}
-
8/9/2019 Input Output Files
52/63
Output of the Program
Enter code number1001
Enter number of items193Enter cost452
Code Number : 1001]Item cost : 452.0Total Items : 193Total Cost : 87236.0
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
53/63
Creating a file using text fields in windowsCopyright 2009 by Royal Institute of Information Technology
import java.io.*;import java.awt.*;class StudentFile extends Frame{
//Defining window componentsTextField number, name, marks;Button enter, done;Label numLabel, nameLabel, markLabel;DataOutputStream dos;
//Initialize the Framepublic StudentFile(){
super(Create Student File);}//Setup the windowpublic void setup(){
resize(400, 200);setLayout(new GridLayout (4, 2));
number = new TextField(25);numLabel = new Label(Roll Number);name = new TextField(25);nameLabel = new Label(Student name);marks = new TextField(25);markLabel = new Label(Marks);enter = new Button(ENTER);done = new Button(DONE);
(Continued)
-
8/9/2019 Input Output Files
54/63
Program (Continued) Copyright 2009 by Royal Institute of Information Technology//Add the components to the Frame
add(numLabel);add(number);add(nameLabel);add(name);add(markLabel);add(marks);add(enter);add(done);
show();//open the filetry{
dos = new DataOutputStream(newFileOutputStream(student.dat));}catch(IOException e){
System.err.println(e.toString());System.exit(1);
}}//Write to the filepublic void addRecord(){
int num;Double d;num = (new Integer (number.getText())).intValue();
(Continued)
-
8/9/2019 Input Output Files
55/63
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 fieldsnumber.setText( );
name.setText( );marks.setText( );
}//Adding the record and clearing thepublic void cleanup(){
if(! number.getText().equals( )){addRecord();
}
try{dos.flush();dos.close();
}catch(IOException e) { }
}
(Continued)
-
8/9/2019 Input Output Files
56/63
Program (Continued) Copyright 2009 by Royal Institute of Information Technology
//Processing the event
public boolean action (E vent event, object o){if(event.teg instanceof Button){
if(event.arg.equals(ENTER)){addRecord();return true;
}}return super.action(event, o);
}public boolean handleEvent(Event event){
if(event.get instanceof Button){if(event.arg.equals(DONE)){
cleanup();System.exit(0);return true;
}
}return super.handleEvent(event);
}//Execute the programpublic static void main(String args[]){
StudentFile student = newStudentFile();student.setup();
}
}
-
8/9/2019 Input Output Files
57/63
Output of the Program
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
58/63
Other Stream Classes
Object Streams
Piped Streams
Pushback Streams
Filtered Streams
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
59/63
Object Streams
It is also possible to perform input and outputoperations on objects using the object streams.
The object streams are created usingObjectInputStream andObjectOutputStream classes.
We may declare records as objects and use theobject classes to write and read these objects
from files.
This process is known as object serialization.
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
60/63
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 ofPipedInputStream to an object of
PipedOutputStream. The objects inputPipe and outputPipe are
connected using the connect() method.
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
61/63
Threads using pipes to communicate
Copyright 2009 by Royal Institute of Information Technology
Write Thread Read Thread
inputPipe outputPipe
-
8/9/2019 Input Output Files
62/63
Pushback Streams
The pushback streams created by the classesPushbackInputStream andPushbackReadercan be used to push a singlebyte or a character back into the input stream sothat it can be reread.
When a character indicating a new input token isread, it is pushed back into the input streamuntil the current input token is processed.
Copyright 2009 by Royal Institute of Information Technology
-
8/9/2019 Input Output Files
63/63
Filtered Streams Java supports two abstract classes, namely,
FilterInputStream andFilterOutputStreamthat provides the basic capability to create input and
output streams for filtering input/output in anumber of ways.
These streams, known as Filters, sit between aninput stream and an output stream and perform
some optional processing on the data they transfer
Copyright 2009 by Royal Institute of Information Technology
Filter 1 Filter 2 Filter 3
Inputstream
utputstream