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

).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....
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...
in java File encryption is the science of writing the contents of a file in a...
in java File encryption is the science of writing the contents of a file in a secret code. Write an encryption program that works like a filter, reading the contents of one file, modifying the data into a code, and then writing the coded contents out to a second file. The second file will be a version of the first file, but written in a secret code. Although there are complex encryption techniques, you should come up with a simple...
in Java please For this assignment you are to write a class that supports the addition...
in Java please For this assignment you are to write a class that supports the addition of extra long integers, by using linked-lists. Longer than what is supported by Java's built-in data type, called long. Your program will take in two strings, consisting of only digits, covert each of them to a linked-list that represents an integer version on that string. Then it will create a third linked-list that represents the sum of both of the linked lists. Lastly, it...
Create a Java class file for a Car class. In the File menu select New File......
Create a Java class file for a Car class. In the File menu select New File... Under Categories: make sure that Java is selected. Under File Types: make sure that Java Class is selected. Click Next. For Class Name: type Car. For Package: select csci2011.lab7. Click Finish. A text editor window should pop up with the following source code (except with your actual name): csci1011.lab7; /** * * @author Your Name */ public class Car { } Implement the Car...
1. Download the EXCEL file: Access Exercise Tables 2. Open a new blank database in ACCESS...
1. Download the EXCEL file: Access Exercise Tables 2. Open a new blank database in ACCESS and name it “Exercise-Your Name” where you replace Your Name with your name. 3. Import each worksheet in the EXCEL file into ACCESS as a separate table as follows: a. External Data Tab -> Import Excel icon b. In the dialog box browse for the destination of the excel file you saved in step 1, it should default to “import the source data in...
Move the file “nfile2” into the “unix” directory. Copy the file “nfile1” into the “java” directory....
Move the file “nfile2” into the “unix” directory. Copy the file “nfile1” into the “java” directory. Show how you would create the files “test1”, “test2”, & “test3” in the “test” directory to ensure that they have the same file creation date/time. From the ~ folder, use the * and then the [ ] wildcard procedures to list all the files in the “test” directory. From the directory structure above, give an example of a relative path & an absolute path....
Describe the rules governing identifiers. Can identifiers be re-used in the same Java class file? Provide...
Describe the rules governing identifiers. Can identifiers be re-used in the same Java class file? Provide three examples of different kinds of invalid identifiers. Java
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT