Saturday 3 August 2013

43:Random Access Files

Learning Objectives
After completing this session, you will be able to:
‰  Apply Random Access Files
Random Access File
Random access files permit nonsequential, or random, access to the contents of a file.
Problem Scenario
Consider the archive format known as ZIP. A ZIP archive contains files and is typically
compressed to save space. It also contain a directory entry at the end that indicates where the
various files contained within the ZIP archive begin, as shown in the following figure:
Suppose that you want to extract a specific file from a ZIP archive. If you use a sequential access
stream, then you have to:
‰  Open the ZIP archive
‰  Search through the ZIP archive until you locate the file you want to extract
‰  Extract the file
‰  Close the ZIP archive
Using the procedure referred in the earlier slide,on average, you would have to read half the ZIP
archive before finding the file that you want to extract.
You can extract the same file fromthe ZIP archive more efficiently by using the seek feature of a
random access file and following these steps:
‰  Open the ZIP archive
‰  Seek to the directory entry and locate the entryfor the file you want to extract from the
ZIP archive
‰  Seek (backward) within the ZIP archive to the position of the file to extract
‰  Extract the file
‰  Close the ZIP archive
Benefits of Random Access File
Random Access File algorithm is more efficientbecause you read only the directory entry and the
file that you want to extract.
java.io.RandomAccessFile
‰  The java.io.RandomAccessFile class implements both the DataInput and DataOutput
interfaces.
‰  The java.io.RandomAccessFile class can be used for both reading and writing.
Creating a Random Access File
Similar to the sequential FileInputStream and FileOutputStream classes, you specify a file to be
opened by name when you instantiate an object of class RandomAccessFile. You can specify the
file name either by a literal string or by passing a File object which you have previously
instantiated.
Unlike with the sequential classes, when you instantiate an object of RandomAccessFile, you must
indicate whether you will just be reading the file, or also writing to it. You must be able to read a file
before you can write to it.
The syntax for instantiating a RandomAccessFile object is as follows:
new RandomAccessFile(name, mode)
As mentioned earlier, the name can be specified using either a literal string or an object of type
File.
The mode is a literal string which can be either of two possibilities:
‰  "r" means open for reading only
‰  "rw" means open for both reading and writing
Once the file is opened you can use the various forms of the read___() and write___() methods to
read and write the data in the file.
The following code creates a RandomAccessFile to read the file named xanadu.txt:
new RandomAccessFile("xanadu.txt", "r");
This one opens the same file for both reading and writing:
new RandomAccessFile("xanadu.txt", "rw");
After the file has been opened, you can use the common read or write methods defined in the
DataInput and DataOutput interfaces to perform I/O on the file.
File Pointer
‰  RandomAccessFile supports the notion of a file pointer.
‰  The file pointer indicates the current location in the file.
‰  When the file is first created, the file pointer is set to zero, indicating the beginning of
the file.
‰  Calls to the read and write methods adjust the file pointer by the number of bytes read
or written.
RandomAccessFile Methods
‰  RandomAccessFile contains the normal file I/O methods for implicitly manipulating the
file pointer.
‰  RandomAccessFile also contains the following three methods for explicitly
manipulating the file pointer:
o  int skipBytes(int):Moves the file pointer forward the specified number of
bytes
o  void seek(long):Positions the file pointer just before the specified byte
o  long getFilePointer():Returns the current byte location of the file pointer
Try It Out
Problem Statement:
Write a program that illustrates the usage of RandomAccessFile.
Code:
import java.io.*;
public class RandomIOApp {
public static void main(String args[]) throws IOException {
RandomAccessFile file = new RandomAccessFile("test.txt",
"rw");
file.writeBoolean(true);
file.writeInt(123456);
file.writeChar('j');
file.writeDouble(1234.56);
// Use seek() to move to a specific file location
file.seek(1);
System.out.println(file.readInt());
System.out.println(file.readChar());
System.out.println(file.readDouble());
file.seek(0);
System.out.println(file.readBoolean());
file.close();
}
}
How It Works:
‰  The RandomIOApp programprovides a simple demonstration of the capabilities of
random-access I/O.
‰  It writes a boolean, int, char, and double value to a file and then uses the seek()
method to seek to offset location 1 within the file. This is the position after the first byte
in the file.
‰  It then reads the int, char, and double values from the file and displays them to the
console window.
‰  Next, it moves the file pointer to the beginning of the file and reads the boolean value
that was first written to the file.
‰  This value is also written to the console window.
‰  The output of the program is as follows:
123456
j
1234.56
True
Tips and Tricks:
What is the difference between the File and RandomAccessFile classes?
Solution:The File class encapsulates the files and directories of the local file system. The
RandomAccessFile class provides the methods needed to directly access data contained in any
part of a file.
Summary
‰  Random access files permit nonsequential, or random, access to the contents of a file.
‰  The RandomAccessFile class implements both the DataInput and DataOutput
interfaces and therefore can be used for both reading and writing.
‰  RandomAccessFile supports the notion of a file pointer.
‰  RandomAccessFile contains the following three methods for explicitly manipulating the
file pointer.
o  skipBytes:Moves the file pointer forward the specified number of bytes.
o  seek:Positions the file pointer just before the specified byte.
o  getFilePointer:Returns the current byte location of the file pointer.
Test Your Understanding
1.State true or false for the following:
a)RandomAccessFile is the onlybidirectional stream in Java.
b)A random access file can be opened in ‘r’ mode or ‘rw’ mode.

No comments:

Post a Comment