Chapter03 Files
Chapter03 Files
Chapter 03
1
Objectives
After studying this chapter, students should be able to learn:
Streams
Byte Stream
Text Stream
Files
Creating a file
Writing to a file
Reading from a file
Object Serialization
File Class
2
Streams
A Stream represents flow of data from one place to another
place.
Input Streams reads or accepts data.
Output Streams sends or writes data to some other place.
All streams are represented as classes in java.io package.
The main advantage of using stream concept is to achieve
hardware independence. This is because we need not change the
stream in our program even though we change the hardware.
Streams are of two types in Java:
1. Byte Streams
2. Character or Text Streams
3
Byte Streams
Handle data in the form of bits and bytes.
Byte streams are used to handle any characters (text), images,
audio and video files.
For example, to store an image file (.gif or.jpg), we should go
for a byte stream.
To handle data in the form of 'bytes' the abstract classes:
InputStream and OutputStream are used.
The important classes of byte streams are:
FileInputStream/FileOutputStream: They handle data to be read or
written to disk files.
FilterInputStream/FilterOutputStream: They read data from one
stream and write it to another stream.
ObjectInputStream/ObjectOutputStream: They handle storage of
objects and primitive data.
4
Byte Stream Classes
5
Character or Text Streams
Handle data in the form of characters.
Character or text streams can always store and retrieve data in the
form of characters (or text) only.
It means text streams are more suitable for handling text files like the ones
we create in Notepad.
They are not suitable to handle the images, audio or video files.
To handle data in the form of ‘text’, the abstract classes: Reader
and Writer are used.
The important classes of character streams are:
BufferedReader/BufferedWriter: - Handles characters (text) by buffering
them. They provide efficiency.
CharArrayReader/CharArrayWriter: - Handles array of characters.
InputStreamReader/OutputStreamWriter: - They are bridge between byte
streams and character streams. Reader reads bytes and then decodes them
into 16-bit unicode characters. Writer decodes characters into bytes and then
writes.
PrintReader/PrintWriter: - Handle printing of characters on the screen.
6
Text Stream Classes
7
File
A file represents organized collection of data.
Data is stored permanently in the file.
Once data is stored in the form of a file we can use it in
different programs.
8
Byte Stream Example
Program 1: Write a program to read data from the keyboard and write it to a text file
using byte stream classes.
import java.io.*;
class Create1
{
public static void main(String args[]) throws IOException
{ //attach keyboard to DataInputStream
DataInputStream dis = new DataInputStream (System.in);
//attach the file to FileOutputStream
FileOutputStream fout = new FileOutputStream ("myfile");
//read data from DataInputStream and write into FileOutputStream
char ch;
System.out.println ("Enter @ at end : " ) ;
while( (ch = (char) dis.read() ) != '@' )
fout.write (ch);
fout.close ();
}
}
9
Example2
Program 2: Write a program to improve the efficiency of writing data into a file using
BufferedOutputStream.
import java.io.*;
class Create2
{ public static void main(String args[]) throws IOException
{ //attach keyboard to DataInputStream
DataInputStream dis = new DataInputStream (System.in);
//attach file to FileOutputStream, if we use true then it will open in append mode
FileOutputStream fout = new FileOutputStream ("myfile", true);
BufferedOutputStream bout = new BufferedOutputStream (fout, 1024);
//Buffer size is declared as 1024 otherwise default buffer size of 512 bytes is used.
//read data from DataInputStream and write into FileOutputStream
char ch;
System.out.println ("Enter @ at end : " ) ;
while ( (ch = (char) dis.read() ) != '@' )
bout.write (ch);
bout.close ();
fout.close ();
}
}
10
Example3
Program 3: Write a program to read data from myfile using FileInputStream.
//Reading a text file using byte stream classes
import java.io.*;
class Read1
{ public static void main (String args[]) throws IOException
{ //attach the file to FileInputStream
FileInputStream fin = new FileInputStream ("myfile");
//read data from FileInputStream and display it on the monitor
int ch;
while ( (ch = fin.read() ) != -1 )
System.out.print ((char) ch);
fin.close ();
}
}
11
Example4
Program 4: Write a program to improve the efficiency while reading data
from a file using BufferedInputStream.
import java.io.*;
class Read2
{ public static void main(String args[]) throws IOException
{ //attach the file to FileInputStream
FileInputStream fin = new FileInputStream ("myfile");
BufferedInputStream bin = new BufferedInputStream (fin);
//read data from FileInputStream and display it on the monitor
int ch;
while ( (ch = bin.read() ) != -1 )
System.out.print ( (char) ch);
fin.close ();
}
}
12
Example5
Program 5: Write a program to create a text file using character or text
stream classes.
import java.io.*;
class Create3
{ public static void main(String args[]) throws IOException
{ String str = "This is an Institute" + "\n You are a student"; // take a String
//Connect a file to FileWriter
FileWriter fw = new FileWriter ("textfile");
//read chars from str and send to fw
for (int i = 0; i<str.length () ; i++)
fw.write (str.charAt (i) );
fw.close ();
}
}
13
Example6
Program 6: Write a program to read a text file using character or text stream
classes.
import java.io.*;
class Read3
{ public static void main(String args[]) throws IOException
{ //attach file to FileReader
FileReader fr = new FileReader ("textfile");
//read data from fr and display
int ch;
while ((ch = fr.read()) != -1)
System.out.print ((char) ch);
//close the file
fr.close ();
}
}
14
Object Serialization
Serialization is the process of storing object contents into a file.
The class whose objects are stored in the file should implement
"Serializable' interface of java.io package.
Serializable interface is an empty interface without any members and
methods, such an interface is called 'marking interface' or 'tagging
interface'.
Marking interface is useful to mark the objects of a class for a special
purpose.
For example, 'Serializable' interface marks the class objects as
'serializable' so that they can be written into a file.
If serializable interface is not implemented by the class, then writing that
class objects into a file will lead to NotSerializableException.
static and transient variables cannot be serialized.
De-serialization is the process of reading back the objects from
a file.
15
Example
Program 7: Write a program to create Employ class whose objects is to be stored
into a file.
import java.io.*;
import java.util.*;
class Employ implements Serializable
{ private int id;
private String name;
private float sal;
private Date doj;
Employ (int i, String n, float s, Date d)
{ id = i;
name = n;
sal = s;
doj = d;
}
void display ()
{
System.out.println (id+ "\t" + name + "\t" + sal + "\t" + doj);
}
16
static Employ getData() throws IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
System.out.print ("Enter employ id : ");
int id = Integer.parseInt(br.readLine());
System.out.print ("Enter employ name : ");
String name = br.readLine ();
System.out.print ("Enter employ salary : " );
float sal = Float.parseFloat(br.readLine ());
Date d = new Date ();
Employ e = new Employ (id, name, sal, d);
return e;
}
}
17
Example2
Program 8: Write a program to show serialization of objects.
//ObjectOutputStream is used to store objects to a file
import java.io.*;
import java.util.*;
class StoreObj
{ public static void main (String args[]) throws IOException
{ BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
FileOutputStream fos = new FileOutputStream ("objfile");
ObjectOutputStream oos = new ObjectOutputStream ( fos );
System.out.print ("Enter how many objects : ");
int n = Integer.parseInt(br.readLine () );
for(int i = 0;i<n;i++)
{ Employ e1 = Employ.getData ();
oos.writeObject (e1);
}
oos.close ();
fos.close ();
}
}
18
Example3
Program 9: Write a program showing deserialization of objects.
//ObjectInputStream is used to read objects from a file
import java.io.*;
class ObjRead
{ public static void main(String args[]) throws Exception
{ FileInputStream fis = new FileInputStream ("objfile");
ObjectInputStream ois = new ObjectInputStream (fis);
try
{ Employ e;
while ( (e = (Employ) ois.readObject() ) != null)
e.display ();
}
catch(EOFException ee)
{
System.out.println ("End of file Reached...");
}
finally
{ ois.close ();
fis.close ();
}
}
} 19
File Class
File class of java.io package provides some methods to know
the properties of a file or a directory.
We can create the File class object by passing the filename or
directory name to it.
File obj = new File (filename);
File obj = new File (directoryname);
File obj = new File ("path", filename);
File obj = new File ("path", directoryname);
20
21
Example
Program 10: Write a program that uses File class methods and display file
properties.
import java.io.*;
class FileProp
{ public static void main(String args[])
{ String fname = args [0];
File f = new File (fname);
System.out.println ("File name: " + f.getname ());
System.out.println ("Path:"+ f.getPath ());
System.out.println ("Absolute Path:"+ f.getAbsolutePath ());
System.out.println ("Parent:"+ f.getParent ());
System.out.println ("Exists:"+ f.exists ());
if ( f.exists() )
{ System.out.println ("Is writable: "+ f.canWrite ());
System.out.println ("Is readable: "+ f.canRead ());
System.out.println ("Is executable: "+ f.canExecute ());
System.out.println ("Is directory: "+ f.isDirectory ());
System.out.println ("File size in bytes: "+ f.length ());
}
}
} 22
Output:
23
Self -Review Questions
24