Unit Vi Managing Input Output Files in Java
Unit Vi Managing Input Output Files in Java
In java, io package supports java‟s basic Input Output System including file input/
output operations.
6.1 Streams
Stream is an abstraction that either produces or consumes information. In other
words, stream is a flow of data. Java streams can be classified as input streams and
output streams.
Input stream refers to flow of data from any source to the program. Output
stream refers to flow of data from the program to any destination. Various sources and
destinations are shown in figure 6.1.
Keyboard Keyboard
Mouse Mouse
Disk Disk
Network Network
Figure 6.1: Sources & destinations of Data flow
Program reads data from source of data through input stream as shown in figure
6.2.
reads
Source Input Stream > Java Program
writes
Java Program Output Stream > Destination
Character
Byte Stream
Stream
Classes
Classes
Output
Input Stream Reader Writer
Stream
Classes Classes Classes
Classes
Object
InputStrea
m
FileInp PipeInp ByteArrayI FileInp StringBuffe Sequence
ObjectInput
utStrea utStrea nputStrea utStrea rInputStrea InputStre
Stream
m m m m m am
DataInp Pushbac
BufferedInp
utStrea kInputStr
utStream
m eam
DataInpu
t
(interfac
e)
Figure 6.5: InputStream Classes
Various methods of InputStream Classes are as follows,
Method Usage
read( ) Reads a byte
read(byte b[ ]) Reads array of bytes
read(byte b[ ], int n, int m) Reads m number of bytes into array b[ ] starting
from nth byte
available( ) Returns number of bytes available in input stream
skip(int n) Skips n bytes from input stream
reset( ) Goes back to beginning of stream
close( ) Closes the input stream
Object
OutputStrea
m
FileOut PipeOut ByteArray FileOut StringBuffe Sequence
ObjectOutp
putStre putStrea OutputStre putStre rOutputStr OutputSt
utStream
am m am am eam ream
DataOut Pushbac
BufferedOut
putStrea kOutput
putStream
m Stream
DataOut
put
(interfac
e)
Figure 6.6: OuputStream Classes
Various methods of OutputStream Classes are as follows,
Method Usage
write( ) Writes a byte
write(byte b[ ]) Writes array of bytes
write(byte b[ ], int n, int m) Writes m number of bytes from array b[ ] starting
from nth byte
close( ) Closes the output stream
flush( ) Flushes output stream
Reader
Characte
Buffered InputStreamR
rArrayRe FilterReader PipeReader StringReader
Reader eader
ader
FileReader PushbackReader
Object
Writer
Charact
Buffere OutputStrea PipeWrite StringWrite PrintW
erArray FilterWriter
dWriter mWriter r r riter
Writer
FileWriter
Exception Usage
EOFException This exception signals that end of file or end of
stream has been reached
FileNotFoundException This exception informs that file could not be found
InterruptedIOException This exception warns that Input/ Output operation is
interrupted
IOException This exception signals that some sort of Input/ Output
exception has occurred.
While creating a file, we should also decide type of data that may be handled by
the file to be created. The type of data that may be handled may include bytes,
characters or primitive types.
We should also decide purpose of creating the file. e.g. reading only, writing only
or both operations.
For handling a file, we have to define a file stream. For reading data, file stream
can be defined using FileReader class or FileInputStream class. Similarly for writing
data, file stream can be defined using FileWriter or FileOutputStream class.
While creating file stream object, constructor may be used for providing
associated filename. This can be done in two ways.
Direct way:
FileInputStream fis;
try
{
fis = new FileInputStream(“Sample01.txt”);
----
}
catch(IOException e)
{
----
}
Indirect way:
File infile = new File(“Sample01.txt”);
FileInputStream fis;
try
{
fis = new FileInputStream(infile);
----
}
catch(IOException e)
{
----
}
//Example 1
//Program for copying contents of one file into another
import java.io.*;
class FileCopy
{
public static void main(String args[ ])
{
File infile = new File(“myfile1.dat”);
File outfile = new File(“myfile2.dat”);
FileReader rd;
FileWrter wt;
try
{
rd = new FileReader(infile);
wt = new FileWriter(outfile);
int ch;
while((ch = rd.read( )) != -1)
{
w.write(ch);
}
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
try
{
rd.close( );
wt.close( );
}
catch(IOException e)
{
}
}
}
}
//Example 2
//Program for counting number of words and lines from a file
import java.io.*;
class FileCount
{
public static void main(String args[ ])
{
File infile = new File(“myfile1.dat”);
FileReader rd;
int lines = 0;
int words = 0;
try
{
rd = new FileReader(infile);
int ch;
while((ch = rd.read( )) != -1)
{
if(ch == „\n‟)
{
lines++;
words++;
}
else if(ch == „ ‟ || ch == „\t‟)
{
words++;
}
}
System.out.println(“Files contains ”+lines+“ lines ”+“ and ”+words+“ words”);
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
try
{
rd.close( );
}
catch(IOException e)
{
}
}
}
}
//Example 3
//Program for copying contents of one file into another
import java.io.*;
class FileByteCopy
{
public static void main(String args[ ])
{
FileInputStream infile;
FileOutputStream outfile;
byte b;
try
{
infile = new FileInputStream(“file1.dat”);
outfile = new FileOutputStream(“file2.dat”);
do
{
b = (byte)infile.read( );
outfile.write(b);
}while(b != -1);
}
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)
{
}
}
}
}
//Example 4
//Program for writing into file (Creating a file)
import java.io.*;
class FileCreate
{
public static void main(String args[ ])
{
FileOutputStream outfile;
byte b[ ] = {„G‟, „o‟, „ ‟, „C‟, „o‟, „r‟, „o‟, „n‟, „a‟};
try
{
outfile = new FileOutputStream(“file3.dat”);
outfile.write(b);
}
catch(IOException e)
{
System.out.println(e.getMessage( ));
}
finally
{
try
{
outfile.close( );
}
catch(IOException e)
{
}
}
}
}
//Example 5
//Program for reading from a file
import java.io.*;
class FileRead
{
public static void main(String args[ ])
{
FileInputStream outfile;
byte b;
try
{
infile = new FileInputStream(“file3.dat”);
while((b = infile.read( )) != -1)
{
System.out.println((char)b);
}
}
catch(IOException e)
{
System.out.println(e.getMessage( ));
}
finally
{
try
{
infile.close( );
}
catch(IOException e)
{
}
}
}
}
//Example 6
//Program for writing data of primitive data type into a file
// and reading that data (of primitive data type) from the file
import java.io.*;
class FilePrimitive
{
public void writePrimitive( )
{
try
{
File f = new File(“file4.dat”);
FileOutputStream fos = new FileOutputStream(f);
DataOutputStream do = new DataOutputStream(fos);
do.writeInt(459);
do.writeChar(„C‟);
do.writeDouble(1.92);
do.writeBoolean(False);
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
try
{
do.close( );
fos.close( );
}
catch(IOException e)
{
}
}
}
Sample Questions:
1. Define Stream class. List its types. [2M]
2. Distinguish between input stream class and output stream class. [4M]
3. List the methods of File Input Stream class. [2M]
4. Explain the following classes. [4M]
i) Byte Stream Class ii) Character Stream Class
5. Write any two methods from Character Stream Classes. [2M]
6. Enlist types of stream classes and describe methods for reading and writing data for
each type. [4M]
7. Give any two methods from File class with their usage.[2M]
8. Write a program to copy content of one file to another file. [4M]
9. Write a program to copy content of one file into another file. [4M]
10. Write a program to perform following task. [6M]
i) Create a text file and store data in it.
ii) Count number of lines and words in that file
11. Write a program to count number of words from a text file using stream classes.
[4M]
12. Write a program to count number of words from a text file using stream classes.
[4M]