How can I create a Random Access File record without specifying the number of records?

171 Views Asked by At

Here the registration number is given as 100, what I want is;

Instead of determining the number of records from the beginning, I want the number of records to increase as I add records.

I will exemplify what I want to tell through arrays;

Not so;

Array[100];
Array[0]=data;

Like this;

Array[];
Array.push(data);
import com.deitel.jhtp6.ch24.RandomAccessAccountRecord;
import java.io.IOException;
import java.io.RandomAccessFile;

public class CreateRandomFile {
    private static final int NUMBER_RECORDS = 100;

    public void createFile() {
        RandomAccessFile file = null;
        try {
            file = new RandomAccessFile("clients.dat", "rw");
            RandomAccessAccountRecord blankRecord = new RandomAccessAccountRecord();
            for (int count = 0; count < NUMBER_RECORDS; count++) 
                blankRecord.write(file);
            System.out.println("Created file clients.dat.");
            System.exit(0);
        } catch (IOException ioException) {
            System.err.println("Error processing file.");
            System.exit(1);
        } finally {
            try {
                if (file != null) 
                    file.close();
            } catch (IOException ioException) {
                System.err.println("Error closing file.");
                System.exit(1);
            }
        }
    }
}

It can be done by counting the number of recordings and adding +1 each time, but this is not practical or professional at all.

1

There are 1 best solutions below

10
Pavel On

If you don't know the number of the records in advance, then you should not use a for loop, but rather a different construct. A while loop with a check if there are still accounts records to write to file left would do for example. I don't understand the code logic though, you initialise one instance of RandomAccessAccountRecord blankRecord = new RandomAccessAccountRecord(); and then call the write method on the same instance hundred times?

I don't get this one either:

Not so; Array[100]; Array[0]=data;

Like this; Array[]; Array.push(data);

Does that mean that you need a data structure which will be initialised as empty and you would dynamically add elements? Then array is not the best choice for that.