OBJECT ORIENTED
PROGRAMMING
Java I/O
Prepared by
Dr. Abinash Tripathy
School of Computer Application
KIIT Deemed to be University, Bhubaneswar
Java File
• In Java, with the help of File Class, we can work with files.
• This File Class is inside the [Link] package.
• The File class can be used by creating an object of the class and then
specifying the name of the file.
Why File Handling Needed
• File Handling is an integral part of any programming language as file
handling enables us to store the output of any particular program in a
file and allows us to perform certain operations on it.
• In simple words, file handling means reading and writing data to a file.
Streams in Java
• In Java, a sequence of data is known as a stream.
• This concept is used to perform I/O operations on a file.
• There are two types of streams :
• Input Stream
• Output Stream
INPUT STREAM
• The Java InputStream class is the superclass of all input streams.
• The input stream is used to read data from numerous input devices like the
keyboard, network, etc.
• InputStream is an abstract class, and because of this, it is not useful by itself.
• However, its subclasses are used to read data.
• There are several subclasses of the InputStream class, which are as follows:
1. AudioInputStream
2. ByteArrayInputStream
3. FileInputStream
4. ObjectInputStream
5. StringBufferInputStream
Methods in InputStream
Method Description
read() Read one bits of data from input stream
read( byte [] array) Reads byte from the stream and stores that byte in the specified
array.
mark() It marks the position in the input stream until the data has been
read.
reset() Returns the control to the point where the mark was set inside
the stream.
skips () Skips and removes a particular number of bytes from the input
stream.
close () Close the input stream
Output Stream
• The output stream is used to write data to numerous output devices like the
monitor, file, etc.
• OutputStream is an abstract superclass that represents an output stream.
• OutputStream is an abstract class and because of this, it is not useful by itself.
However, its subclasses are used to write data.
• There are several subclasses of the OutputStream class which are as follows:
1. ByteArrayOutputStream
2. FileOutputStream
3. StringBufferOutputStream
4. ObjectOutputStream
5. DataOutputStream
6. PrintStream
Methods in OutputStream
Method Description
write() Write the specified bit to Output stream
write ( byte [] array) Writes the bytes which are inside a specific array to the output
stream.
close () Close the output stream
flush() Force to write all the data present in an output stream to the
destination.
Types of streams
• Based on the data types, streams can be classified as
1. Byte Stream
2. Character or text stream
• Byte streams represent data in the form of individual bytes where as Character stream
represent data as the character each of 2 bytes.
• If a class name ends with the word “Stream”, then it comes under Byte Stream i.e.,
InputStream reads bytes and OutputStream write bytes. If a class ends with the word “
Reader” or “Writer” , then it is considered as Character Stream i.e. Reader reads text and
Write writes text
• Byte Streams are used to handle any characters, images, audios and video files. For
example: for storing an image file, we should go for byte stream. Character Stream can
store and retrieve data in the form of character only, i.e., it is suitable for handling text files.
Creating file using FileOutputStream
• First, we read the data from keyboard. For that purpose, we should add keyboard to some input
stream class. The code for using DataInputStream class for reading data from keyboard is as:
DataInputStream dis = new DataInputStream ([Link]);
• Then, we have to attach a file where data is stored. Here, we take the help of FileOutputStream
which can send data to file. Attaching the file “[Link]” to FileOutputStream can be done as:
FileOutputStream fout = new FileOutputStream (“[Link]”);
• The next step is to read data from DataInputStream and write it into FileOutputStream, i.e., read
data from dis object and write it into fout object
ch = (char) [Link]();
[Link](ch);
• Finally , any file need to be closed after preforming the input and output operation, else data of
the file may be corrupted. Closing this file is done by closing the associated streams
[Link]();
Program to create a file using FileOutputStream
import [Link].*;
class Create
{
public static void main (String args[])throws IOException
{
DataInputStream dis = new DataInputStream([Link]);
FileOutputStream fout = new FileOutputStream("[Link]");
[Link]("Enter text (@ at the end):");
char c;
while((c = (char) [Link] ()) != '@')
[Link](c); • In this program, we read the data from the keyboard
[Link](); and write it to [Link]
} • The program accepts data from the keyboard till the
} user types @ when he does not want to continue
Reading data from a file using FileInputStream
• First, we have to attach the file to a FileInputStream as shown below:
FileInputStream fin = new FileInputStream (“[Link]”)
• This will enable us to read data from the file, then to read the data from the file,
we should read data from FileInputStream as
ch = [Link]();
• The read () reads all characters from the file, till it reach the end of the file. When
there is no more data available to read futher, the read() returns -1;
• Then, we have to attach the monitor to some output steam. For displaying the
data, we can use [Link] which is nothing but PrintStream object.
[Link](ch);
• Finally, we have to close the file
[Link]();
Reading data from a file using FileInputStream
import [Link].*;
class Read
{
public static void main (String args[])throws IOException
{
FileInputStream fin = new FileInputStream("[Link]");
[Link]("File contents");
int ch;
while((ch = [Link]()) != -1)
[Link]((char)ch);
[Link]();
}
}
Create a File using FileWriter
import [Link].*;
class Create1
{
public static void main (String args[]) throws IOException
{
String Str = "This is a book on Java" + "\n I am a student of MCA";
FileWriter fw = new FileWriter ("[Link]");
for(int i = 0; i < [Link](); i++)
{
[Link]([Link](i));
} In this program, we are taking a string where the
[Link](); characters are read and written into a FileWriter,
which is attached to a file named [Link]
}
}
Reading a file using FileReader
import [Link].*;
class Read1
{
public static void main (String args[])throws IOException
{
int ch;
FileReader fr = null;
try{
fr = new FileReader("[Link]");
}
catch(FileNotFoundException fe){
[Link]("file not found");
return;
} • In this program, the [Link] is attached to
while((ch=[Link]())!= -1) FileReader for reading file.
[Link]((char)ch); • It is read using read() method and is displayed
[Link](); on the monitor.
}
}
Storing strings into a file using FileWriter
• We have written data in the form of character into a text. It is possible
to write data in the form of strings also.
• We can write string by string into a text file.
• The readLine() method of BufferedReader class can read a string, that
method used to read string from the keyboard.
• Then using the write() method of FileWriter class, we can write the
string into the text file.
Program to store string by string into a text file
import [Link].*;
class Create2
{
public static void main (String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
String s;
FileWriter fw = new FileWriter("[Link]");
[Link]("Enter data : ");
while(!(s = [Link]()).equals("exit"))
[Link](s+"\n");
[Link]();
• We are attaching “\n” at the end of each string, it is
}
to store the string line by line into text file.
}
• If “\n” is not there, all the strings are stored in the
file in the same line as a single string, which will
create a problem while reading the strings from the
file
Reading strings from a file using FileReader
• readLine() method of BufferedReader can read a string of characters,
this method is used to read string by string from the text file.
• But, BufferedReader should be connected to FileReader as this stream
can actually read the data from the text file.
• To read string, readLine() method of BufferedReader class. When
readLine() method could not read a string from the file, it means it
reach end of the file and hence, it will return ‘null’.
• The ‘null’ represents a null object, an object that does not exist.
Program to read String by String from a text file
import [Link].*;
class Read2
{
public static void main (String args[]) throws IOException
{
String s;
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
while((s=[Link]()) != null)
[Link](s);
[Link]();
}
}