Question

In: Computer Science

describe the mechanism that supports random file access in Java.

describe the mechanism that supports random file access in Java.

Solutions

Expert Solution

`Hey,

Note: Brother if you have any queries related the answer please do comment. I would be very happy to resolve all your queries.

The heart of the random access file mechanism is the class called java.io.RandomAccessFile. It has all the capabilities of FileInputStream and FileOutputStream. The instance of this class not only helps in creating or opening an existing file but also provide a parameter to specify the mode of operation such as read(r) or write(w) whien opening a file. We can almost visualize a random access file as an array of bytes stored in the file system. An array location, as we know, can be directly accessed if we supply an appropriate index number.

In much the same way, records in the random access file can be directly accessed with the index number supplied through the seek method and subsequently read/write chunks of data from/to the file. Whien traversing through the records, to ascertain if we have reached the end of file, we can either compare the current position of the file pointer (by using the getFilePointer method, which returns the current offset) with the total length of the file itself or, more simply, look for the occurrence of EOFException. EOFException is thrown when the file pointer tries to access beyond the end of file mark of the file. However, if any other error occurs other than EOFException, an IOException is thrown.

Implementing a CRUD Operation

CRUD is basically a database operation. Here we implement it to simulate a database-like implementation of a flat file. Because flat files are not meant to operate like a database, here, the Java code is more of a jugglery to achieve this end. However, this fun exercise can not only enrich you conceptually but also give you an glimpse of actual database storage structure and how difficult/easy is to create one from scratch. The code is simple enough to understand. However, simplification sometime overshadows important details; so is the case here. A lot of detail validation and verification is simply ignored. Nevertheless, one can always modify the following code to achieve a greater end once the basic concept is grasped.

public class FileDatabase {
   RandomAccessFile file;

   public FileEditor(String fileString)
         throws IOException {
      file = new RandomAccessFile(fileString, "rw");
   }

   public void close() throws IOException {
      if (file != null)
         file.close();
   }

   public PersonRecord getRecord(int id) throws IOException {
      PersonRecord record = new PersonRecord();
      if (id < 1)
         throw new IllegalArgumentException("invalid ID!!");
         file.seek((id - 1) * PersonRecord.SIZE);
         record.readFromFile(file);
         return record;
   }

   public void insertRecord(PersonRecord record)
         throws IllegalArgumentException, IOException {
      if (getRecord(record.getId()).getId() != 0)
         System.out.println("Cannot add new.
            Record already exists.");
      else {
         file.seek((record.getId() - 1) * PersonRecord.SIZE);
         record.writeToFile(file);
      }
   }

   public void updateRecord(PersonRecord record)
         throws IllegalArgumentException, IOException {
      if (getRecord(record.getId()).getId() == 0)
         System.out.println("Cannot update.
            Record does not exist.");
      else {
         file.seek((record.getId() - 1) * PersonRecord.SIZE);
         record.writeToFile(file);
      }
   }

   public void deleteRecord(PersonRecord record)
         throws IllegalArgumentException, IOException {
      if (getRecord(record.getId()).getId() == 0)
         System.out.println("Cannot delete.
            Record does not exist.");
      else {
         file.seek((record.getId() - 1) * PersonRecord.SIZE);
         record = new PersonRecord();
         record.writeToFile(file);
      }
   }

   public void showAllRecords() {
      PersonRecord record = new PersonRecord();
      try {
         file.seek(0);
         while (true) {
            do {
               record.readFromFile(file);
            } while (record.getId() == 0);
            System.out.println(record.toString());
         }
      } catch (EOFException ex1) {
         return;
      } catch (IOException ex2) {
         System.err.println("error reading file");
      }
   }
}

To test, we can supply some dummy data as follows:

public class Test {

   public static void main(String[] args)
         throws IOException {

      FileEditor fe = new FileEditor
         ("/home/mano/temp/people.dat");

      fe.insertRecord(new PersonRecord(1, "Brian", "Sullivan",
         "[email protected]"));
      fe.insertRecord(new PersonRecord(2, "Randal", "Wallace",
         "[email protected]"));
      fe.insertRecord(new PersonRecord(3, "Eric", "Bloch",
         "[email protected]"));
      fe.insertRecord(new PersonRecord(4, "Kapil", "Ansari",
         "[email protected]"));
      fe.showAllRecords();
      fe.updateRecord(new PersonRecord(4,"Tony","Li",
         "[email protected]"));
      fe.showAllRecords();
      fe.deleteRecord(new PersonRecord(1,"Brian","Sullivan",
         "[email protected]"));
      fe.showAllRecords();
      fe.close();
   }

}

Kindly revert for any queries

Thanks.


Related Solutions

In reference to network access control, describe some of the access control mechanism used by a...
In reference to network access control, describe some of the access control mechanism used by a network administrator to filter, inspect and detect different forms of traffic.
).Modify the project so that records are inserted into the random access file in ascending order...
).Modify the project so that records are inserted into the random access file in ascending order using an insertion sort methodology with the Social Security Number acting as the key value. This requires defining the method compareTo() in the Personal and Student classes to be used in a modified method add() in Database. The method finds a proper position for a record d, moves all the records in the file to make room for d, and writes d into the...
For each of the following file processing operations, indicate whether a sequential file, indexed random file, virtual storage access method, hashing,
For each of the following file processing operations, indicate whether a sequential file, indexed random file, virtual storage access method, hashing, or pointer structure would work best. You may choose as many as you wish for each step. Also, indicate which would perform the least optimally.a. Retrieve a record from the file based on its primary key value.b. Update a record in the file. c. Read a complete file of records. d. Find the next record in a file. e....
1).Modify the project so that records are inserted into the random access file in ascending order...
1).Modify the project so that records are inserted into the random access file in ascending order using an insertion sort methodology with the Social Security Number acting as the key value. This requires defining the method compareTo() in the Personal and Student classes to be used in a modified method add() in Database. The method finds a proper position for a record d, moves all the records in the file to make room for d, and writes d into the...
This laboratory is designed to get you started with the project and random access file I/O....
This laboratory is designed to get you started with the project and random access file I/O. Open your source file and write or copy the code for the class interface for the Sdisk. Class Sdisk { public : Sdisk(string diskname, int numberofblocks, int blocksize); int getblock(int blocknumber, string& buffer); int putblock(int blocknumber, string buffer); int getnumberofblocks(); // accessor function int getblocksize(); // accessor function private : string diskname; // file name of software-disk int numberofblocks; // number of blocks on...
I. Describe the differences between discretionary access control model and mandatory access control model II. File...
I. Describe the differences between discretionary access control model and mandatory access control model II. File permissions in Linux can be also represented in digits from 0-7 for the owner, group and others with reading as the most significant bit (E.g., the value 6 represents the permission right rw- for a file). Suppose a file in Linux has the permission as the digits 764. • What does this permission right indicate for the owner/user, group and others? • What is...
Write program#2 upload .java file. 2A) Write a java program that uses the Random class to...
Write program#2 upload .java file. 2A) Write a java program that uses the Random class to generate a number in the range 21 to 64.  Print the generated number. 2B) Using the Random class and nextInt(6), rolls two die generating two random numbers each in the range 1 through 6. Total by adding the two values together. Print the value of each die, and the total value. 2C) Using the Math class and sqrt(num), calculate the square root of integer twenty-two...
Write program#2 upload .java file. 2A) Write a java program that uses the Random class to...
Write program#2 upload .java file. 2A) Write a java program that uses the Random class to generate a number in the range 21 to 64.  Print the generated number. 2B) Using the Random class and nextInt(6), rolls two die generating two random numbers each in the range 1 through 6. Total by adding the two values together. Print the value of each die, and the total value. 2C) Using the Math class and sqrt(num), calculate the square root of integer twenty-two...
Why is a device such as a tape-drive a poor secondary storage device for Random/Direct access to a file?
Why is a device such as a tape-drive a poor secondary storage device for Random/Direct access to a file?
When using random access files in Java, the programmer is permitted to create files which can...
When using random access files in Java, the programmer is permitted to create files which can be read from and written to random locations. Assume that a file called "integers.dat" contains the following values: 25 8 700 284 63 12 50 Fill in blanks: You are required to write the following Java code statements: (a) create a new stream called, blueray, which allows the program to read from and write to the file, "integers.dat." _____________________ (b) Write a statement which...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT