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.
Asked
Active
Viewed 803 times
1 Answers
1
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;
}

Sebi
- 1,390
- 1
- 13
- 22
-
How do I make sure that os.writeInt() uses only four bytes? If I need to store a text in 8 bytes is there a way to do that also? – Isuru Herath Jul 24 '15 at 16:55
-
It will always save 4 bytes as per spec. See the [Javadoc](http://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html) _Writes an int to the underlying output stream as four bytes, high byte first._ – Sebi Jul 24 '15 at 17:03