0% found this document useful (0 votes)
22 views

Unit Vi Managing Input Output Files in Java

Uploaded by

xboyxman1000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Unit Vi Managing Input Output Files in Java

Uploaded by

xboyxman1000
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Unit – IV

Managing Input/ Output/ Files in Java


06 Hours
08 Marks

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.

Sources of Data Destination of Data

Keyboard Keyboard

Mouse Mouse

Memory Java Program Memory

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

Figure 6.2: Read from Input Stream


Program writes data to destination of data through output stream as shown in
figure 6.3.

writes
Java Program Output Stream > Destination

Figure 6.3: Write to Output Stream

6.2 Stream Classes


The java.io package contains large number of stream classes. They may be
categorized into two groups on the basis of type of data on which they operate as,
- Byte Stream classes (operate on bytes i.e. binary data)
- Character Stream classes (operate on characters i.e. Unicode)
The classification of Stream classes is shown in figure 6.4.
Java Stream
Classes

Character
Byte Stream
Stream
Classes
Classes

Output
Input Stream Reader Writer
Stream
Classes Classes Classes
Classes

Figure 6.4: Classification of Stream Classes

6.3 Byte Stream Classes

6.3.1 InputStream Classes


These classes are used for reading 8-bit bytes.

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

Various methods of DataInput class are as follows,


Method Usage
readShort( ) Reads a short type of data
readInt( ) Reads a integer type of data
readLong( ) Reads a long type of data
readFloat( ) Reads a float type of data
readDouble( ) Reads a double type of data
readLine( ) Reads a line of data (as a String)
readChar( ) Reads a character type of data
readBoolean( ) Reads a boolean type of data

6.3.2 OutputStream Classes


These classes are used for writing 8-bit bytes.

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

Various methods of DataInput class are as follows,


Method Usage
writeShort( ) Writes a short type of data
writeInt( ) Writes a integer type of data
writeLong( ) Writes a long type of data
writeFloat( ) Writes a float type of data
writeDouble( ) Writes a double type of data
writeLine( ) Writes a line of data (as a String)
writeChar( ) Writes a character type of data
writeBoolean( ) Writes a boolean type of data

6.4 Character Stream Classes

6.4.1 Reader Classes


These classes are used for reading characters.
Object

Reader

Characte
Buffered InputStreamR
rArrayRe FilterReader PipeReader StringReader
Reader eader
ader

FileReader PushbackReader

Figure 6.5: Reader Classes

6.4.2 Writer Classes


These classes are used for writing characters.

Object

Writer

Charact
Buffere OutputStrea PipeWrite StringWrite PrintW
erArray FilterWriter
dWriter mWriter r r riter
Writer

FileWriter

Figure 6.6: Writer Classes

6.4.3 Using Streams


Following table shows which classes from Character Stream classes and Byte
Stream classes are used for performing specified tasks.

Sr. Task Class used from Class used from Byte


No. Character Stream Stream Classes
Classes
1 Performing input operation Reader InputStream
2 Buffering input BufferedReader BufferedInputStream
3 Reading from a file FileReader FileInputStream
4 Performing output operation Writer OutputStream
5 Buffering output BufferedWriter BufferedOutputStream
6 Writing to a file FileWriter FileOutputStream

6.5 Using File class


The java.io package includes class known as File which supports various
operations related to file as follows,
- Creating a file
- Opening a file
- Closing a file
- Deleting a file
- Getting name of a file
- Getting size of a file
- Checking existence of file
- Renaming a file
- Checking whether file is writable
- Checking whether file is readable

6.5.1 Input Output Exceptions


Various exceptions related to input and output are explained below.

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.

6.5.2 Creation of files


While creating a disk file, proper filename must be given to it. The filename
uniquely identifies the file on the disk. Maximum number of characters and characters
allowed in the filename depends on operating system. Filename may contain two parts
as filename and extension. Some example filenames are
file.dat test.txt salary.data application.doc Sample01

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)
{
----
}

6.5.3 Reading/ Writing characters from/ to files

//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)
{
}
}
}
}

6.5.4 Reading/ Writing bytes from/ to files

//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)
{
}
}
}
}

6.5.5 Handling Primitive Data types


Up to previous topic, we have handled either characters or bytes only. But for
reading and writing data of primitive data type Filter classes like DataInputStream and
DataOutputStream classes are used.

//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)
{
}
}
}

public void readPrimitive( )


{
try
{
File f = new File(“file4.dat”);
FileInputStream fis = new FileOutputStream(f);
DataInputStream di = new DataInputStream(fis);
System.out.println(do.readInt( ));
System.out.println(do.readChar( ));
System.out.println(do.readDouble( ));
System.out.println(do.readBoolean( ));
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
try
{
di.close( );
fis.close( );
}
catch(IOException e)
{
}
}
}

public static void main(String args[ ])


{
FilePrimitive fp = new FilePrimitive( );
fp.writePrimitive( );
fp.readPrimitive( );
}
}

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]

You might also like