Chapter 10
Chapter 10
Files are the primary source and destination for storing the data contained in
programs. Java provides the java.io package for performing I/O operations. The
java.io package includes the File class, which provides support for creating various
files and directories. The File class describes the properties of a File object and
provides various methods for storing and retrieving the contents from a file.
The File class in the java.io package provides various methods to access the
properties of a file or a directory, such as file permissions, date and time of creation,
and path of a directory. A directory stores files and other directories in it and is
created using the File class. An object of the File class represents a file or a directory.
You can use the following constructors to create an instance of the File class:
File(File dirObj, String filename): Creates a new instance of the File class. The
dirObj argument is a File object that specifies a directory. The filename argument
specifies the name of the file.
File(String directoryPath): Creates a new instance of the File class. The directoryPath
argument specifies the path of the file.
File(String directoryPath, String filename): Creates a new instance of the File class.
The argument directoryPath specifies the path of the file, and the filename argument
specifies the name of the file. The various methods of the File class are:
String getName(): Retrieves the name of the specified file.
String getParent(): Retrieves the name of the parent directory.
String getPath(): Retrieves the path of the specified file.
String[] list(): Displays the list of files and directories inside the specified directory.
You can use the following code to access the properties of a file or a directory:
import java.io.*;
class Files
{
public static void main(String args[])throws NullPointerException
{
String dirName = "C:/Test";
File f = new File(dirName, "work.txt");
File f3 = new File(dirName, "renFile.txt");
System.out.println("File name is:" +f.getName());
System.out.println("Path of the file is:" +f.getPath());
System.out.println("Parent directory is:" +f.getParent());
}}}
In the preceding code, an instance of the work.txt file is created using the File class.
The Files class shows information such as path and parent directory of the work.txt file.
If the work.txt file contains text, the File class lists the contents of the file.
Random access files enable you to access the contents of a file in a non-sequential
manner. These files enable you to read and write text and bytes to any location in a
file. Random access files are not derived from any InputStream or OutputStream. On
the other hand, these files implement the DataInput and DataOutput interfaces,
which define the basic I/O operations.
You access the random files in Java by using the RandomAccessFile class. The
constructor throws FileNotFoundException, if the RandomAccessFile class is unable
to retrieve the name of the file to be created. You can use the following constructors
to create an instance of the RandomAccessFile class:
RandomAccessFile(File fileObj, String mode): Creates an instance of the random
access file. The argument fileObj specifies the name of the file to be opened as a File
object. The mode argument specifies the access permissions assigned to a file. The mode
argument can accept the following values:
r: Opens a file in the read-only mode.
rw: Opens a file in the read/write mode.
rws: Opens a file in the read/write mode. The rws mode ensures that each update made
to the file data or metadata is immediately updated to the storage device, such as hard
disk. Metadata is defined as a component of data that provides information about data,
such as name, content, and
quality of data.
rwd: Opens a file in the read/write mode. The rwd mode ensures that each update made
to the file data is immediately updated to the underlying storage device.
import java.io.*;
public class TestRandomFile
{
public static void main(String args[])
{
RandomAccessFile file=null;
try
{
file=new RandomAccessFile("work.txt","rw");
file.writeInt(85);
file.writeChar('V');
file.seek(0);
System.out.println(file.readInt());
System.out.println(file.readChar());
file.seek(file.length());
file.writeBoolean(true);
file.seek(3);
System.out.println(file.readBoolean());
file.close();
} catch(IOException e)
{
System.out.println("Exception: " +e);
}
}}
In the preceding code, the TestRandomFile class opens the work.txt file in the
read/write mode. If the file does not exist, then the RandomAccessFile class creates
the specified file. The write() method of the RandomAccessFile class is used to write
in the work.txt file. The read() method of the RandomAccessFile class is used to read
from the work.txt file and displays the values on the screen using the System.out.println()
method.
A Java program uses streams to either read data items from a source or to write data
items to a destination. I/O operations consist of two parts, data that is entered into a
program through an input source, such as a keyboard and the processed data that is
returned through an output source, such as a monitor. Programs in Java perform I/O
operations with the help of streams. A stream is a passage through which the data items
flow from a source, such as a program, to a destination, such as a file.
Stream sources include files and memory buffers, and stream destinations include the
same entities as stream sources and other entities, such as monitor. In an input stream,
data items flow from the source. Similarly, in an output stream data items flow to a
destination. Input stream refers to the flow of data into a program and output stream
refers to the flow of data out of the program.
In Java, the java.io package consists of various I/O stream classes and interfaces that
support I/O operations, such as reading from a file or keyboard and writing to a file or
monitor. Streams in Java are of two types, byte streams and character streams. The basic
unit of a byte stream is a byte, and the basic unit of a character stream is a Unicode
character.
Input streams are the byte streams that read data in the form of bytes. Java provides the
InputStream class to perform input operations. The InputStream class is an abstract class
that enables its subclasses to read data from different sources, such as a file and keyboard
and displays the data on the monitor. Some of the methods of the InputStream class are:
int read(): Reads the next byte of data from an input stream. It returns –1 if it
encounters the end of a stream.
int read(byte b[]): Reads the number of bytes from the array specified by the b[]
argument. The read() method returns –1 when the end of the file is encountered.
int read(byte b[], int offset, int length) throws IOException: Reads the number of bytes
from the array specified by the b[] argument. The argument offset specifies the starting
position for the read operation, and length specifies the number of bytes to be read. The
read() method returns –1 when
the end of the file is encountered.
available(): Returns the total number of bytes available for reading in a stream.
long skip(long n) throws IOException: Ignores the specified number of bytes from an
input stream.
mark(int nbyte): Places a mark at the current point in the input stream and this mark
remains until the specified data bytes are read.
reset(): Places the file pointer to the previously set mark or at the beginning of the
stream.
System.in Object
The System class in the java.lang package has a static member variable, in that
refers to the keyboard. The in variable is an instance of the InputStream class and is
used to read data from the keyboard. You can use the following code to create the
Testin class that uses System.in object to read a line of text from the keyboard:
public class Testin
{
public static void main(String args[])
{
byte buffer[]=new byte[80];
System.out.println("Type the text to be displayed ");
try
{
System.in.read(buffer);
} catch(Exception e)
{
System.out.println("Exception: "+e.toString());
}
String str=new String(buffer);
System.in.read() method. */
System.out.println(str);
}
}
In the preceding code, the Testin class reads the input that a user types from the keyboard
using the System.in.read() method. The input read is displayed on the screen using the
System.out.println() method.
You can use the following code to create the TestFileInput class to implement the
FileInputStream class:
import java.io.*;
public class TestFileInput
{
public static void main(String args[])
{
byte buffer[]=new byte[100];
try
{
FileInputStream class. */
FileInputStream file=new FileInputStream("filein.txt");
file.read(buffer,0,50);
} catch(Exception e)
{
System.out.println("Exception: "+e.toString());
}
String str=new String(buffer);
System.out.println(str);
}}
In the preceding code, the TestFileInput class creates an instance of the
FileInputStream class to read data from the existing file, filein.txt file. If the file does
not exist, then the program displays a run-time error. The TestFileInput class
displays the contents of the filein.txt file on the screen.
In the preceding syntax, a new FileReader object is constructed where fileObj is the File
Object that specifies the file to read the content from. The constructor of the FileReader
class may throw the FileNotFoundException exception in certain conditions, which are:
The fileObj object does not exist.
The fileObj object is not a File class object, but a directory object.
The fileObj object cannot be opened for reading.
You can use the following code to use the FileReader class to read content from a file:
import java.io.*;
public class TestFileReader
{
public static void main(String args[])
{
try
{
File file=new File("Name.txt");
FileReader f=new FileReader(file);
int ch;
while((ch=f.read())!=-1) //Loop till end of file.
{
System.out.print((char)ch);
}
}
catch(FileNotFoundException fnfe)
{
System.out.println("Exception: "+fnfe.toString());
}
catch(IOException ioe)
{
System.out.println("Exception: "+ioe.toString());
}
} //End of main()
}
In the preceding code, the f object reads the Name.txt file that already exists by using
the read() method. The read() method of the FileReader class reads one character
at a time until the end of file is reached and then prints it on the standard output
screen. The following figure shows the content of the Name.txt file:
The BufferedReader Class
The BufferedReader stream reads text from a character input stream and attaches a buffer
to the character input Streams. Buffers allow reading more than one character at a time
and increasing the performance of streams by buffering the input data. The
BufferedReader class allows you to wrap any subclass of the Reader class into a buffered
stream and, therefore increases the performance. The BufferedReader class has various
types of constructors. The syntax of one of the constructors of the
BufferedReader class is:
BufferedReader(Reader StreamObj)
In the preceding syntax, an object of the BufferedReader class is constructed with
the default size of the buffer. The syntax of another constructor of the
BufferedReader class is:
BufferedReader(Reader StreamObj, int BuffSize)
In the preceding syntax, an object of the BufferedReader class is constructed where
the BuffSize parameter specifies the size of the input buffer.
The buffering of a character input stream allows moving forward and backward in the
stream within the available buffer. The mark() and reset() methods implemented in the
BufferedReader class allow file pointer to move forward and backward in the buffer. You
can use the following code to use the BufferedReader stream to read
data from a stream:
import java.io.*;
public class TestBuffer
{
public static void main(String args[])
{
System.out.print("Please enter a string:");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in)); //creates an instance of
BufferedReader class
String str=new String();
try
{
str=br.readLine(); //Reads a line of text into str
}
catch(IOException ioe)
{
System.out.println("Exception: "+ioe.toString());
}
System.out.print("The string entered is: ");
System.out.println(str);
} //End of main()
}
In the preceding code, the br object of the BufferedReader class is created and it
buffers the text written at the command prompt. The readLine() method of the
BufferedReader class reads a line of text at a time.
The FileWriter Class
The FileWriter class writes character data to a file, but does not define any methods of
its own. It derives all methods from its base classes, such as the Writer and the
OutputStreamReader classes. The FileWriter class has various constructors. The
following table lists various constructors of the FileWriter class:
All the constructors of the FileWriter class throw the IOException exception in
certain conditions, which are:
The named file cannot be opened.
The named file exists, but is not an object of the File class.
The named file does not exist and cannot be created.
You can use the following code to write to a file using the write() method of the
FileWriter class:
import java.io.*;
public class TestFileWriter
{
public static void main (String args[])
{
String str="Character Stream Classes in Java";
try
{
FileWriter fout = new FileWriter("stream.txt" );
fout.write(str, 0, str.length() );
fout.close();
}
catch (IOException ioe)
{
System.out.println("Exception: " + ioe.toString());
}
}
}
In the preceding code, the FileWriter class writes to the stream.txt file. Thewrite() method
of the FileWriter class writes the complete text of the str objectinto the stream.txt file.
The following figure shows the content of the stream.txtfile after the execution of the
preceding code:
The BufferedWriter Class
The BufferedWriter class extends the Writer class and writes text to a character
output stream. The BufferedWriter stream attaches a buffer to the character output
Streams. Buffer allows writing more than one character at a time. Buffer reduces the
number of times data is written to the character output stream and therefore, increases the
performance of the stream. The BufferedWriter class allows you to wrap any subclass of
the Writer class into a buffered stream and increases its performance. The BufferedWriter
class has various constructors. The syntax of one
of the constructors of the BufferedWriter class is:
BufferedWriter(Writer outputStream)
In the preceding syntax, an object of the BufferedWriter class is constructed that uses the
output buffer of default size. The syntax of another constructor of the BufferedWriter
class is:
BufferedWriter(Writer outputStream, int bufSize)
In the preceding syntax, an object of the BufferedWriter class is constructed where the
bufSize variable specifies the size of the output buffer. It throws the
IllegalArgumentException exception if the value of the bufSize variable is less than
or equal to 0.
You can use the following code to write to a file using the write() method of the
BufferedWriter class:
import java.io.*;
public class TestBWriter
{
public static void main(String args[])
{
int ch;
BufferedWriter bw=null;
System.out.print("Enter text(terrminate by pressing ctrl +
z):");
try
{
bw=new BufferedWriter(new FileWriter("buffer.txt"));
while((ch=System.in.read())!=-1) //Loop till end of
file.
{
bw.write(ch);
}
bw.flush();
}
catch(IOException ioe)
{
System.out.println("Exception: "+ioe.toString());
}
}
}
The transient keyword
The data members of a class that are not required to be serialized are declared as
transient. The serialization process ignores the transient variables. The syntax of
declaring a variable as transient is:
transient String password;
Using the ObjectInputStream Class for I/O Operations
The ObjectInputStream class extends the InputStream class and implements the
ObjectInput interface. The ObjectInputStream stream deserializes the primitive data and
objects that are written using the ObjectOutputStream stream.
You can use the following code to read an object from a file using the
ObjectInputStream class:
//Code to deserialize a Date object.
import java.io.*;
import java.util.Date;
public class TestObjectInput
{
public static void main(String args[]) throws
IOException,ClassNotFoundException
{
FileInputStream fis=new FileInputStream("myfile.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
String str=(String)ois.readObject();
Date date=(Date)ois.readObject();
System.out.println(str+date);
}
}
A class implements the Serializable interface in order to serialize its objects. The class
that implements the Serializable interface may be a user-defined class. The
writeObject() method is used to write an object of the serialized class, and the
readObject() method is used to read the serialized object. You can use the following
code to define the Employee class that implements the Serializable interface: