You are on page 1of 32

Mr. Prashant S.

Bhandare

Name of staff: - Mr. BhandareP. S.


Name of Subject: - Java Programming
Subject code: - 22412
Class: - SYCO
Department: - Computer Engineering

Chapter 6
Managing input & output files in
java

-by-
Prof. Bhandare P. S.
SVERI’s COE(Poly), Pandharpur

Hours: 06
Marks: 08

Subject Name: - Java Programming (22412) 1 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

Syllabus:
1. Introduction and Concept of Streams.
2. Stream Classes.
3. Byte Stream Classes: Input Stream Classes, Output Stream Classes.
4. Character Stream Classes, Using streams.
5. Using File Class: I/O Exceptions, Creation of Files, Reading/Writing
characters, Reading/Writing Bytes, Handling Primitive Data types.
Assignment no. 5
6. Write any four methods of file class with their use.(4M)(S-17)
7. What is Iterator class ? Give syntax and use of any two methods of Iterator
class.(4M) (S-17)
8. What is use of ArrayListclass ? State any two methods with their use from
ArrayList. (4M) (S-17)
9. Draw the hierarchy of Writer stream classes, and hierarchy of Reader stream
classes.(4M)(w-16)
10.Explain methods of map class and set class in jdk frame work. (4M) (w-16)
(s-16)
11.What are stream classes ? List any two input stream classes from character
stream.(4M) (s-16)
12.Explain serialization with stream classes.(4M) (s-16)
13.What are streams ? Write any two methods of character stream
classes.(4M)(w-15)
14.Write any two methods of File and FileInputStream class each.(4M)(w-15)
15.Write syntax and function of following methods of Date class : (4M)(s-15)
1. i) getTime( )
2. ii) getDate ()

Subject Name: - Java Programming (22412) 2 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

Programs

1. Write a program that will count no. of characters in a file.(4M)(w-16)


2. Write a java program to copy contents of one file to another file.(4M)(w-16)
3. Write a program to copy contents of one file to another file using character
stream class.(4M)(s-15)
About Title of Chapter:
 The title of chapter “File I/O & collection frame work ” gives idea that in this
chapter students are going to learns one of the most important concept
regarding File handling.
 Also Student are going to learn what are the different collection frame work
used in java.
About Central Idea of Chapter
 The central idea of the chapter is that the new concept File operations &
different collection frameworks are elaborated here.
 This chapter is mainly included in the syllabus student should understand the
basics for file & collections.
Importance of Chapter
 This chapter is important because it gives introduction to new programming
language File handling.
 Also this chapter is important as it includes defining different collections&
working on that frameworks.
 Also it includes study of different operations performed on File like reading
file, writing to file, copy file data to another file.
Objectives of chapter
 By studying this chapter student will able to learn.
1. How file class is used to create File & what are the operations
performed on that file.
2. What is mean by stream classes & how they are used.
3. What is by serialization how it is handled.
4. How FileReader&FileWriter classes are used in file handling.
5. What are the differnet collection classes used in java.

Subject Name: - Java Programming (22412) 3 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

Introduction
 So far we have used variables and arrays for storing data inside the programs.
 This approach poses the following problems.
 1. The data is lost either when a variable goes out of scope or when the
program is terminated. That is, the storage is temporary.
 2. It is difficult to handle large volumes of data using variables and
arrays.
 We can overcome these problems by storing data on secondarystorage
devices such as floppydisks or harddisks.
 The data is stored in these devices using the concept of files.
 Datastored in files is often called persistentdata.
 A file is a collection of relatedrecords placed in a particular area on the disk.
 A record is composed of several fields and a field is a group of characters as
illustrated in Fig.
 Characters in JavaareUnicodecharacters composed of twobytes, each byte
containing eight binary digits, 1 or 0.
 Storing and managing data using files is known as fileprocessing which
includes tasks such as creatingfiles, updatingfiles and manipulation of data.
 Reading and writing of data in a file can be done at the level of bytes or
characters or fields depending on the requirements of a particular application.
 Java also provides capabilities to read and write class objects directly.
 Note that a record may be represented as a classobject in Java.
 The process of reading and writing objects is called objectserialization.

Concept of Streams
 In file processing, input refers to the flow of datainto a program and output
means the flow of dataout of a program.

Subject Name: - Java Programming (22412) 4 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 Input to a program may come from the keyboard, the mouse, the memory,
the disk, a network, or anotherprogram.
 Similarly, output from a program may go to the screen, the printer, the
memory, the disk, a network, or anotherprogram.
 This is illustrated in Fig. below

Keyboard Keyboard

Mouse Mouse

Memory Memory
Java
Program
Disk Disk

Network Network

Program Program
Inpu
Outpu
t
t
 Although these devices look very different at the hardware level, they share
certain common characteristics such as unidirectionalmovement of data,
treating data as a sequence of bytes or characters and support to the
sequentialaccess to the data.
 Java uses the concept of streams to represent the orderedsequence of data a
common characteristic shared by all the inputoutput devices as stated above.
 A stream presents a uniform, easy-to-use, object-oriented interface between
the program and the input/output devices.
 A stream in Java is a path along which dataflows (like a river or a pipe along
which water flows).
 It has a source (of data) and a destination (for that data) as depicted in Fig.
below.
 Both the source and the destination may be physicaldevices or programs or
other streams in the same program.

Subject Name: - Java Programming (22412) 5 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 The concept of sendingdata from one stream to another (like one pipe
feeding into another pipe) has made streams in Java a powerful tool for
fileprocessing.
 We can build a complexfile processing sequence using a series of simple
streamoperations.
 This feature can he used to filter data along the pipeline of streams so that we
obtain data in a desiredformat.
 For example, we can use one stream to get rawdata in binary format and then
use another stream in series to convert it to integers.
 Javastreams are classified into two basic types, namely, inputstream and
outputstream.
 An inputstreamextracts (i.e. reads) data from the source (file) and sends it
to the program. Similarly, an outputstreamtakes data from the program and
sends (i.e. writes) it to the destination (tile).
 Figure below illustrates the use of input and output streams.
 The program connects and opens an Inputstream on the data source and then
reads the dataserially.
 Similarly, the program connects and opens an outputstream to the
destinationplace of data and writesdata out serially.
 In both the cases, the program does not know the details of endpoints (i.e.
source and destination).

Subject Name: - Java Programming (22412) 6 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

Stream Classes
 The java.io package contains a large number of streamclasses that provide
capabilities for processing all types of data.
 These classes may be categorized into twogroups based on the data type on
which they operate.
 1. Bytestream classes that provide support for handlingI/O operations
on bytes.
 2. Characterstream classes that provide support for managing I/O
operations on characters.
 These two groups may further be classified based on their purpose.
 Figure below shows how stream classes are grouped based on their functions

Subject Name: - Java Programming (22412) 7 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

Byte Stream Classes


 Byte stream classes have been designed to provide functional features for
creating and manipulating streams and files for reading and writing bytes.
 Since the streams are unidirectional, they can transmit bytes in only one
direction and, therefore, Java provides two kinds of byte stream classes:
inputstreamclasses and outputstreamclasses.
Input Stream Classes
 Inputstream classes that are used to read8-bitbytes include a super class
known as InputStream and a number of subclasses for supporting various
input-related functions.
 Figure below shows the class hierarchy of inputstreamclasses.

Object

Input Stream

FileInputStream
SequenceInputStream

PipeInputStream
ObjectInputStream

ByteArrayInputStream
StringBufferInputStream

FilterInputStream

BufferedInputStream PushbackInputStream

DataInputStream

DataInput

Subject Name: - Java Programming (22412) 8 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 The super class InputStream is an abstract class, and, therefore, we cannot


create instances of this class.
 Rather, we must use the subclasses that inherit from this class.
 The InputStream class defines methods for performing input functions such
as
 Reading bytes
 Closing streams
 Marking positions in streams
 Skipping ahead in a stream
 Finding the number of bytes in a stream
Table 16.1 gives a brief description of all the methods provided by the InputStream
class.
Method Description

1. read() Reads a byte from the input stream

2. read (byte b[]) Reads an array of bytes into b

3. read (byte b[], int n, int m) Reads m bytes into b starting from nth byte

4. available( ) Gives number of bytes available in the input

5. skip(n) Skips over n bytes from the input stream

6. reset( ) Goes back to the beginning of the %beam

7. close( ) Closes the input stream

 Note that the class DatalnputStream extends FilterinputStream and


implements the interface DataInput.
 Therefore, the DatalnputStream class implements the methods described in
DataInput in addition to using the methods of InputStream class.
 The DataInput interface contains the following methods:
 readShort( ) • readInt( ) • readLong( ) • readFloat( ) • readUTF( )
 • readDouble( ) • readLine( ) • readChar( ) • readBoolean( )

Subject Name: - Java Programming (22412) 9 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

Output Stream Classes


 Output stream classes are derived from the base class OutputStream as shown
in Fig. below.

Object

Output Stream

FileOutputStream
ByteArrayOutputStream

PipeOutputStream
ObjectOutputStream
FilterOutputStream

BufferedOutputStream PushbackOutputStream

DataOutputStream

DataOutput

 Like InputStream the OutputStream is an abstract class and therefore we


cannot instantiate it.
 The several subclasses of the OutputStream can be used for performing the
outputoperations.
 The OutputStream includes methods that arc designed to perform the
following tasks:
 Writingbytes
 Closingstreams
 Flushingstreams
 Table below show brief description of all the methods defined by
outputStream class.
 Summary of OutputStream Methods

Subject Name: - Java Programming (22412) 10 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

Method Description
1. Write() Writes a byte to the output stream
2. write(byte b[]) Writes all bytes in the army b to the output stream
3. writc(byte b[]. int n, int m) Writes m bytes from way b starting from nth byte
4. close( ) Closes the output stream
5. flush( ) Flushes the output stream

 The DataOutputStream, a counterpart of DatalnputStream, implements the


interface DataOutput therefore implements the following methods contained
in the DataOutput Interface.
 • writeShort() •writeInt() •writeLong() •writeFloat()
 • writeUTF()
 • writeDouble() • writeBytes( ) • writeChar( ) • writeBoolean()
Character Stream Classes
 One of the limitations of bytestreamclasses is that it can handle only 8-bitbytes
and cannot work directly with Unicodecharacters.
 To overcome this limitation, characterstream classes have been introduced in
java.iopackage to match the bytestream classes.
 The characterstream classes support 16-bitUnicode characters, performing
operations on characters, characterarrays, or strings, reading or
writingbuffer at a time.
 Character stream classes are divided into twostream classes namely,
Readerclass and Writerclass.
Reader classes
 Readerclasses are used to read 16-bitunicodecharacters from the input
stream.
 The Reader class is the superclass for all character-oriented input stream
classes.
 All the methods of this class throw an IOException.
 Being an abstract class, the Reader class cannot be instantiated hence its
subclasses are used.
 ReaderClasses are functionally very similar to InputStream classes.

Subject Name: - Java Programming (22412) 11 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 Reader Classes are listed in table below.


Class Description
BufferedReader contains methods to read characters from the buffer
CharArrayReader contains methods to read characters from a character array
FileReader contains methods to read from a file
FilterReader contains methods to read from underlying character-input
stream
InputStreamReader contains methods to convert bytes to characters
PipedReader contains methods to read from the connected piped output
stream
StringReader contains methods to read from a string

 Some of these methods along with their description are listed in Table.
Method Description
intread() returns the integral representation of the next available
character of input. It returns -1 when end of file is
encountered
int read (char buffer []) attempts to read buffer. length characters into the buffer and
returns the total number of characters successfully read. It
returns -I when end of file is encountered
int read (char buffer [], attempts to read 'nChars' characters into the buffer starting
intloc, intnChars) at buffer [loc] and returns the total number of characters
successfully read. It returns -1 when end of file is
encountered
void mark(intnChars) marks the current position in the input stream until 'nChars'
characters are read

Subject Name: - Java Programming (22412) 12 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

void reset () resets the input pointer to the previously set mark
long skip (long nChars) skips 'nChars' characters of the input stream and returns the
number of actually skipped characters
boolean ready () returns true if the next request of the input will not have to
wait, else it returns false
void close () closes the input source. If an attempt is made to read even
after closing the stream then it generates IOException

Writer Classes
 Writerclasses are used to write16-bit Unicode characters onto an
outputstream.
 The Writer class is the superclass for all character-oriented output stream
classes .
 All the methods of this class throw an IOException.
 Being an abstract class, the Writer class cannot be instantiated hence, its
subclasses are used.
 WriterStream Classes Like outputstream claws, the writer stream classes are
designed to perform all outputoperations on files.
 Only difference is that while outputstream classes are designed to write bytes,
the writerstream classes art designed to writecharacters.
 This base class provides support for all output operations by defining
methods that are identical to those in OutputStreamclass.

Subject Name: - Java Programming (22412) 13 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 Writer Classes are listed in table below.


Class Description
BufferedWriter Contains methods to write characters to a buffer
FileWriter Contains methods to write to a file
FilterWriter Contains methods to write characters to underlying output
stream
CharArrayWriter Contains methods to write characters to a character array
OutputStreamWriter Contains methods to convert from bytes to character
PipedWriter Contains methods to write to the connected piped input
stream
StringWriter Contains methods to write to a string
The Writer class defines various methods to perform writing operations on output
stream.
Method Description
void write () writes data to the output stream
void write (inti) Writes a single character to the output stream
void write (char buffer []) writes an array of characters to the output stream
void write(char buffer writes 'n' characters from the buffer starting at buffer [loc]
[],intloc, intnChars) to the output stream
void close () closes the output stream. If an attempt is made to perform
writing operation even after closing the stream then it
generates IOException
void flush () flushes the output stream and writes the waiting buffered
output characters
Other Useful I/O classes
 The java.iopackage support many other classes for performing certain
specialized functions
 1. RandomAccessFiles
 2. StreamTokenizer
 The Java.io.RandomAccessFile class file behaves like a large array of bytes
stored in the file system.
 Instances of this class support both reading and writing to a
randomaccessfile.

Subject Name: - Java Programming (22412) 14 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 RandomAccessFile extends Object class and implementsDataOutput,


DataInput, Closeable interfaces.
 The Java.io.StreamTokenizer class takes an input stream and parses it into
"tokens", allowing the tokens to be read one at a time.
 The streamtokenizer can recognize identifiers, numbers, quoted strings, and
various comment styles.
 The class StreamTokenizer, a subclass of object can be used for breaking up
a stream of text from an input text file into meaningfulpieces called tokens.
Using the File Class
 The java.iopackage includes a class known as the File class that provides
support for creatingfiles and directories.
 The class includes several constructors for instantiating the File objects.
 This class also contains several methods for supporting the operations such
as
 • 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 tile is readable
Input/Output Exceptions
 When creatingfiles and performingi/ooperations on them, the system may
generate related exceptions.
 The basic related exception classes and their functions are given in Table.
 I/OException class and their functions
I/O exception Class function
Signals that an end of the file or end of stream has been
EOFException
reached unexpectedly during input
FileNotFoundExceptlon Informs that a file could not be found
InterruptedIOException Warns that an I/O operations has been interrupted
IOException Signals that an I/O exception of some sort has occurred

Subject Name: - Java Programming (22412) 15 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 Each i/ostatement or group of i/ostatements must have an exceptionhandler


around it as shown below or the method must declare that it throws an
I0Exception.
 try {
 ………………
 ………………. // I/O statements
}
 catch (I0Exception e)
{
 ……………………
 ……………………./ / Message output statement
}
Creation of Files
 If we want to create and use a diskFile, we need to decide the following about
the file and its intended purpose:
 Suitable name for the file
 Data type to be stored
 Purpose (reading, writing, or updating)
 Method of creating the file
 A filename is a unique string of characters that helps identify a file on
the disk.
 The length of a filename and the characters allowed are dependent on the OS
on which the Javaprogram is executed.
 A filename may contain two parts, a primaryname and an optional period
with extension.
 Examples:
 input.datasalary
 test.docstudent.txt
 inventoryrand.dat
 Datatype is important to decide the type of filestreamclasses to be used for
handling the data.
 We should decide whether the data to be handled is in the form of characters,
bytes or primitive type.
 The purpose of using a file must also be decided before using it.
 For example, we should know whether the file is created for reading only, or
writing only, or both the operations.

Subject Name: - Java Programming (22412) 16 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 As using file it muse be opened first. This is done by creatingfile& then


linking it with the filename.
 A file Stream can be defined using the classes of Reader/InputStream for
reading data and Writer/OutputStream for writing data.
Common stream classes used for I/O operations
Source or Character Bytes
Destinati
on Read Write Read Write
CharArrayRea CharArrayWri ByteArrayInputStre ByteArrayOutputStr
Memory
der ter am eam
File FileReader FileWriter FileInputStream FileOutputStream
Pipe PipeReader. PipeWriter PipeInputStream PipeOutputStream.
 File object can be initialized by two ways.
 Name of the file provided to constructor is either directly or Indirectly.
 1. Direct approach
 FileInputStreamfis;
 try
{
 fis=new FileInputStream(“ABC.txt”);
}
 Catch(IOException e)
{
 …………….
}
 Indirect approach uses file object that has been initialized with desired file
name.
 E.g.
 File infile =new File(“ABC.txt”);
 FileInputStreamfis;
 try
{
 fis=new FileInputStream(infile);
}
 Catch(IOException e)
{
 …………….}

Subject Name: - Java Programming (22412) 17 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 The code above includes five tasks:


 • Select a filename
 • Declare a File object
 • Give the selected name to the file object declared
 • Declare a file stream object
 • Connect the tile to the file stream object
 Both the approaches arc illustrated in Fig.

fis ABC.txt

Stream object File Name

fis infile ABC.txt

Stream object File object File Name

Reading/Writing Characters
 As pointed out earlier, subclasses of Reader and Writer implement streams
that can handle characters.
 The two subclasses used for handling characters in files are FileReader (for
reading characters) and FileWriter (for writing characters).
 Following program demonstrate reading data from file.
Program for reading characters from file

 import java.io.*;  System.out.print((char)b);


 class readchar {  }
 public static void main(String  fin.close();
arr[]){  }
 FileReader fin=null;  catch(Exception e){
 int b;  System.out.println(e);
 try {  System.exit(-1);
 fin=new  }
FileReader("file.txt");  }
 while((b=fin.read())!=-1)  }
{

Subject Name: - Java Programming (22412) 18 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

Program for writing characters to file


 import java.io.*;
 class writechar{
 public static void main(String arr[]){
 charcities[] = {'M','A','D','R','A','S', '\n', 'G','O‘
,'A','\n','P','U','N','E','\n', 'M','U','M','B','A','I‘ };
 FileWriterfout=null;
 try{
 fout=new FileWriter("myfile.txt");
 fout.write(cities);
 fout.close();
}
 catch(Exception e){
 System.out.println(e);
 System.exit(-1);
}
}
}
Program for coping characters from one file to another file.
 while((ch=ins.read())!=-1){
 import java.io.*;  outs.write (ch);
 class CopyCharacters { }
 public static void main (String }
args []){  catch (IOException e) {
 File inFile=new File  System.out.println (e);
("array.java");  System.exit(-1);
 File outFile = new File }
("array1.txt");  finally {
 FileReader ins=null;  try{
 FileWriter outs =null;  ins.close();
 try {  outs.close();
 ins =new FileReader(inFile); }
 outs = new  catch(IOException e){ }
FileWriter(outFile); }
 intch; } }

Subject Name: - Java Programming (22412) 19 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 This program is very simple. It creates two file objects inFile and outFile and
initializes them with "input.dat" and "output.dat” respectively using the
following code.
 File inFile = new File (“input.dat");
 FlleoutFile = new File (“output.dat");
 The program then creates two file stream objects ins and outs and initializes
them with "null" as follows:
 FileReader ins = null;
 FileWriter outs = null;
 These streams are then connected to the named files using the following code:
 ins = new FileReader (inFile);
 outs = new FileWriter (outFile);
 This connects inFile to the FileReaderstream ins and outFile to the
FileWriter stream outs.
 This essentially means that the files "input.dat" and "output.dat" are opened.
 The statements ch = ins.read ( ) .
 reads a character from the inFile through the input stream Ins and assigns it
to the variable ch.
 Similarly, the statement outs.write (ch) writes the character stored in the
variable ch to the outFile through the outputstreamouts.
 The character -1 indicates the endofthefile and therefore the code while (
(ch=ins.read( ) ) -1)
 causes the lamination of the whileloop when the end of the file is reached.
 The statements
 ins.close ( )
 outs.close ( )
 enclosed in the finally clause close the files created for reading and writing.
 When the program catches anI/O exception, it prints a message and then exits
from execution.
Reading/Writing Bytes
 In Program we have used FileReader and FileWriter classes to read and write
16-bitcharacters.
 However, most file systems use only 8-bitbytes.
 As pointed out earlier, JavaI/O system provides a number of classes that can
handle 8-bit bytes.
 Two commonly used classes for handling bytes are FileInputStream and
FileOutputStream classes.

Subject Name: - Java Programming (22412) 20 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 We can use them in place of FileReader and FileWriter.


Program for reading bytes from file.
 import java.io.*;  System.out.print((char)b);
 class readbytes { }
 public static void main(String  fin.close();
arr[]) { }
 FileInputStream fin=null;  catch(Exception e){
 int b;  System.out.println(e);
 try {  System.exit(-1);
 fin=new }
FileInputStream("file.txt"); }
 while((b=fin.read())!=-1) }
{
Program for writing bytes to file.
 import java.io.*;
 class writeBytes
{
 public static void main(String arr[])
{
 byte cities[]={'M','A','D','R','A','S','\n',
'G','O','A','\n','P','U','N','E','\n','M', 'U','M','B','A','I'};
 FileOutputStreamfout=null;
 try
{
 fout=new FileOutputStream("city.txt");
 fout.write(cities);
 fout.close();
}
 catch(Exception e)
{
 System.out.println(e);
 System.exit(-1);
}
}
}
 Program below demonstrates how FileOutputStream class is used for
writingbytes to a file.

Subject Name: - Java Programming (22412) 21 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 The program writes the names of some cities stored in a bytearray to a new
file named "city.txt".
 We can verify the contents of the life by using the command
 type city.txt

 import java.io.*;
 class writeBytes {
 public static void main(String arr[]){
 byte
cities[]={'M','A','D','R','A','S','\n','G','O','A','\n','P','U','N','E','\n','M','U
','M','B','A','I'};
 FileOutputStreamfout=null;
 try{
 fout=new FileOutputStream("city.txt");
 fout.write(cities);
 fout.close();
 }
 catch(Exception e){
 System.out.println(e);
 System.exit(-1);
 }
 }
 }
 Note that a instantiating a FileOutputStream object with the name of the file
creates and opens the file.
 We may also supply the filename as a command line argument at the time of
execution.
 Remember, there are several forms of write( ) method.
 The one we have used here writes the entirebyte array to the file. Finally, we
close the file opened for writing.
 Program below shows how FilelnputStream class is used for reading bytes
from a file.
 The program reads an existing file and displays its bytes on the screen.
 Remember, before we run this program, we must first create a file for it to
read.
 import java.io.*;  public static void main(String
 class readbytes { arr[])

Subject Name: - Java Programming (22412) 22 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 {  }
 FileInputStream fin=null;  fin.close();
 int b;  }
 Try {  catch(Exception e)
 fin=new  {
FileInputStream(arr[0]);  System.out.println(e);
 while((b=fin.read())!=-  System.exit(-1);
1)  }
{  }
 System.out.print((char)b);  }

 Note that the program requires the filename to be given as a command line
argument.
 Program displays the following when we supply the filename "city.txt".
 Prompt>java readbytes city.txt
 MADRAS
 GOA
 PUNE
 MUMBAI
 Another example code given in Program below uses both FlielnputStream
and FileOutputStream classes to copyfiles.
 We need to provide a sourcefilename for reading and a targetfilename for
writing.
 In the example code, we have supplied file namesdirectly to the constructors
while creatingfilestreams.
 We may also supply them as commandlinearguments.
 in.txt file contains data that is to copied in to out.txt;
 import java.io.*;
 class copybytes{
 public static void main(String arr[]){
 FileInputStream fin=null;
 FileOutputStreamfout=null;
 byte b;
 try{
 fin=new FileInputStream("in.txt");
 fout=new FileOutputStream("out.txt");
 do {

Subject Name: - Java Programming (22412) 23 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 b=(byte)fin.read();
 fout.write(b);
 }while(b!=-1);
 fin.close();
 fout.close();
 }
 catch(FileNotFoundExceptionfe){
 System.out.print(fe);
 }
 catch(Exception e){
 System.out.println(e);
 System.exit(-1);
 }
 }
 }
 Program creates fin and fout streams for handling the input/output operations.
 The program then continuously reads a byte from "in.txt" file (using
finstream) and writes it to "out.txt" file (using foutstream) until the end of
file condition is reached.
 We should avoid writing to an existingtile.
 We may use the exists( )method in the Fileclass to check whether the named
file alreadyexists.
 Example:
 File fout= new File ("out.dat");
 if (fout.exists ( ) ) return ( )
 This program could also be written using FileReader and FileWriter classes.
Handling Primitive Data Types
 These classes use the concept of multipleinheritance as illustrated in Fig.
below and therefore implements all the methods contained in both the parent
class and the interface.
 A data stream for input can be created as follows:
 FileInputStreamfis = new FilelnputStream (infile);
 DataInputStream dis = new DetalnputStream (fis) ;
 These statements first create the input file stream fis and then create the input
data stream dis.

Subject Name: - Java Programming (22412) 24 Chapter 6: Manaing I/O files in java
Mr. Prashant S. Bhandare

 These statements basically wrapdis on Its and use it as a "filter". Similarly,


the following statements create the output data stream dos and wrap it over
the output file stream fin.

 import java.io.*;  FileInputStream


 class freadwriteprimitive { fin=new FileInputStream(f);
 public static void main(String  DataInputStream
arr[]) { dis=new
 try { DataInputStream(fin);
 File f=new  System.out.println(dis.re
File("primitive.txt"); adInt());
 FileOutputStreamfout=  System.out.println(dis.re
new FileOutputStream(f); adBoolean());
 DataOutputStream  System.out.println(dis.re
dos=new adDouble());
DataOutputStream(fout);  System.out.println(dis.re
 dos.writeInt(350); adChar());
 dos.writeDouble(322.34)  dis.close();
;  fin.close();
 dos.writeBoolean(true);  }
 dos.writeChar('M');  catch(IOException e){ }
 dos.close();  }
 fout.close();  }
Serialization

Subject Name: - Java Programming (22412) 25 Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.

 Java provides a mechanism, called object serialization where an object can be


represented as a sequence of bytes that includes the object's data as well as
information about the object's type and the types of data stored in the object.
 After a serialized object has been written into a file, it can be read from the
file and deserialized that is, the type information and bytes that represent the
object and its data can be used to recreate the object in memory.
 Classes ObjectInputStream and ObjectOutputStream are high-level
streams that contain the methods for serializing and deserializing an object.
 The ObjectOutputStream class contains many write methods for writing
various data types, but one method in particular stands out −
 public final void writeObject(Object x) throws IOException
 Similarly, the ObjectInputStream class contains the following method for
deserializing an object −
 public final Object readObject() throws IOException,
ClassNotFoundException

Serializing an Object
• Writing Object to file is called as serialization.
1. import java.io.*;
2. class Employee implements Serializable
3. {
4. public String name;
5. public String address;
6. public int number;
7. }
8. public class SerializeDemo {
9. public static void main(String [] args) {
10. Employee e = new Employee();
11. e.name = "AAA";
12. e.address = "Pandharpur";
13. e.number = 101;
14. try {
15. FileOutputStream fileOut =
16. new FileOutputStream("object.txt");
17. ObjectOutputStream out = new ObjectOutputStream(fileOut);
18. out.writeObject(e);
19. out.close();
20. fileOut.close();
26
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.

21. } catch (IOException i) {


22. i.printStackTrace();
23. }
24. }
25.}
Deserializing an Object
 Reading object from file is called Deserialization.
1. import java.io.*;
2. public class DeserializeDemo {
3. public static void main(String [] args) {
4. Employee e = null;
5. try {
6. FileInputStream fileIn = new FileInputStream("object.txt");
7. ObjectInputStream in = new ObjectInputStream(fileIn);
8. e = (Employee) in.readObject();
9. in.close();
10. fileIn.close();
11. } catch (IOException i) {
12. i.printStackTrace();
13. return;
14. } catch (ClassNotFoundException c) {
15.System.out.println("Employee class not found");
16. c.printStackTrace();
17. return;
18. }
19. System.out.println("Deserialized Employee...");
20. System.out.println("Name: " + e.name);
21. System.out.println("Address: " + e.address);
22. System.out.println("Number: " + e.number);
23. }
24.}

Other Stream Classes


 Object Streams
 We have seen in this chapter how we can read and write characters, bytes, and
primitive data types.

27
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.

 It is also possible to perform input and output operations on objects using the
object streams.
 The object streams are created using the ObjectInputStream and
ObjectOuptutStream classes.
 In this case, we may declare records as objects and use the object classes to
write and read these objects from files.
 As mentioned in the beginning, this process is known as object serialisation.
Piped Streams
 Pipedstreams provide functionality for threads to communicate and
exchange data between them.
 Figure below shows how two threads use pipes for communication.
 The write thread sends data to the read thread through a pipeline that connects
an object of PipedlnputStream to an object of PipedOutputStmtm.
 The objects inputPipe and outputPipe are connected using the connect( )
method.

 The pushbackstreams created by the classes PushbackInputStream and


PushbackReader can he used to push a singlebyte or a character (that was
previously read) back into the inputstream so that it can be reread.
 This is commonly used with parsers When a character indicating a new
inputtoken is read, it is pushedback into the input stream until the current
input token is processed.
 It is then reread when processing of the next inputtoken is initiated.
Filtered Streams

28
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.

 Java supports two abstract classes, namely, FilterInputStream and


FilterOutputStream that provide the basic capability to create input and
output streams for tittering 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.
 We can combine filters to perform a series of filtering operations as shown in
Fig. below.
 Note that we used DatalnputStream and DataOutputStream as filters in the
revious Program for handling primitive type data.

Introduction to Collection Framework


 The collectionsframework which is contained in the java.utilpackage is one
of Java's most powerful sub-systems.
 The collectionsframework defines a set of interfaces and their
implementations to manipulatecollections, which serve as a container for a
group of objects such as a set of words in a dictionary or a collection of mails.
 The collections framework also allows us to store, retrieve, and update a set
of objects.
 It provides an API to work with the datastructures, such as lists, trees, maps,
and sets.
 Collections in java is a framework that provides an architecture to store and
manipulate the group of objects.
 All the operations that you perform on a data such as searching, sorting,
insertion, manipulation, deletion etc. can be performed by JavaCollections.
 Java Collection simply means a single unit of objects.
 Java Collectionframework provides many interfaces (Set, List, Queue,
Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSetetc).

29
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.

Content beyond the syllabus:


Handling Primitive Data Types
 These classes use the concept of multipleinheritance as illustrated in Fig.
below and therefore implements all the methods contained in both the parent
class and the interface.
 A data stream for input can be created as follows:
 FileInputStreamfis = new FilelnputStream (infile);
 DataInputStream dis = new DetalnputStream (fis) ;
 These statements first create the input file stream fis and then create the input
data stream dis.
 These statements basically wrapdis on Its and use it as a "filter". Similarly,
the following statements create the output data stream dos and wrap it over
the output file stream fin.

 import java.io.*;  dos.writeDouble(322.34)


 class freadwriteprimitive { ;
 public static void main(String  dos.writeBoolean(true);
arr[]) {  dos.writeChar('M');
 try {  dos.close();
 File f=new  fout.close();
File("primitive.txt");  FileInputStream
 FileOutputStreamfout= fin=new FileInputStream(f);
new FileOutputStream(f);  DataInputStream
 DataOutputStream dis=new
dos=new DataInputStream(fin);
DataOutputStream(fout);  System.out.println(dis.re
 dos.writeInt(350); adInt());

30
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.

 System.out.println(dis.re  dis.close();
adBoolean());  fin.close();
 System.out.println(dis.re  }
adDouble());  catch(IOException e){ }
 System.out.println(dis.re }
adChar()); }
Other Stream Classes
 Object Streams
 We have seen in this chapter how we can read and write characters, bytes, and
primitive data types.
 It is also possible to perform input and output operations on objects using the
object streams.
 The object streams are created using the ObjectInputStream and
ObjectOuptutStream classes.
 As mentioned in the beginning, this process is known as object serialisation.
Piped Streams
 Pipedstreams provide functionality for threads to communicate and
exchange data between them.
 Figure below shows how two threads use pipes for communication.
 The write thread sends data to the read thread through a pipeline that connects
an object of PipedlnputStream to an object of PipedOutputStmtm.
 The objects inputPipe and outputPipe are connected using the connect( )
method.

 The pushbackstreams created by the classes PushbackInputStream and


PushbackReader can he used to push a singlebyte or a character (that was
previously read) back into the inputstream so that it can be reread.
 It is then reread when processing of the next inputtoken is initiated.

31
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java
Mr. Bhandare P.S.

Filtered Streams
 Java supports two abstract classes, namely, FilterInputStream and
FilterOutputStream that provide the basic capability to create input and
output streams for tittering 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.
 We can combine filters to perform a series of filtering operations as shown in
Fig. below.
 Note that we used DatalnputStream and DataOutputStream as filters in the
revious Program for handling primitive type data.

32
Subject Name: - Java Programming (22412) Chapter 6: Manaing I/O files in java

You might also like