write 8 bytes legth records to a file in java

811 views Asked by At

I need to store fixed size records to a file. Each record has two Ids which share 4bytes per each. I'm doing my project in x10-language. If you can help me with x10 code it would be great. But even in Java, your support will be appreciated.

1

There are 1 answers

2
Sebi On

Saving

DataOutputStream os = new DataOutputStream(new FileOutputStream("file.dat"));
os.writeInt(1234); // Write as many ints as you need
os.writeInt(2345);

Loading

DataInputStream is = new DataInputStream(new FileInputStream("file.dat"));
int val = is.readInt(); // read the ints
int val2 = is.readInt();

Example of saving an array of data structures

This example doesn't create fixed-length records, but may be useful:

Let's say you have a data structure

class Record {
    public int id;
    public String name;
}

You can save an array of the records like so:

void saveRecords(Record[] records) throws IOException {
    DataOutputStream os = new DataOutputStream(new FileOutputStream("file.dat"));

    // Write the number of records
    os.writeInt(records.length);
    for(Record r : records) {
        // For each record, write the values
        os.writeInt(r.id);
        os.writeUTF(r.name);
    }

    os.close();
}

And load them back like so:

Record[] loadRecords() throws IOException {
    DataInputStream is = new DataInputStream(new FileInputStream("file.dat"));

    int recordCount = is.readInt(); // Read the number of records

    Record[] ret = new Record[recordCount]; // Allocate return array
    for(int i = 0; i < recordCount; i++) {
        // Create every record and read in the values
        Record r = new Record(); 

        r.id = is.readInt();
        r.name = is.readUTF();
        ret[i] = r;
    }

    is.close();

    return ret;
}