Question: 37.11 File Random Access In this program you will use RandomAccessFile to read and write a binary file (Binary.dat). Step 1) Create a RandomAccessFile object

37.11 File Random Access

In this program you will use RandomAccessFile to read and write a binary file (Binary.dat).

Step 1) Create a RandomAccessFile object for the Binary.dat file. Use the 'rws' tag to ensure that changes happen immediately. Create a ArrayList of type Long as well.

Stepl 2) The data in Binary.dat is organized logically as sets of triples: a price (double, 8 bytes), an amount (int, 4 bytes), and a description (UTF string, indefinite). Use the readDouble(), readInt(), and readUTF() methods of RandomAccessFile to read these triples until the end of the file is reached. The most straightforward way to do this is to get the length of Binary.dat (use the length() method of RandomAccessFile) before the loop and then repeat the loop as long as the current position (use getFilePointer() of RandAccessFile to get this) is less than the file length. After you read each triple, display the values on a line separate by a space and also save the current file position on the ArrayList (use the RandomAccessFile method getFilePointer() to get the current file position). You program should display the following:

2.49 24 carrots 10.99 100 paper cups 5.49 20 premium saltines 3.69 30 eggs 6.79 15 apples 9.99 20 lunch box 4.49 15 ham sandwich 

Submit your code to pass Test 1.

Step 3)

Write a loop that goes through the Binary.dat file and increases all of the prices by 5%. You will need to use the seek() and writeDoublle() of RandomAccessFile. The values that you saved in the ArrayList will be helpful. Submit your code. to pass Test 2.

import java.io.*; import java.util.*;

public class FileRandomAccess {

public static void main(String [] args) { /* Replace this comment with your code. */ } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!