我需要将固定大小的记录存储到文件中。每条记录有两个id,每个id共享4字节。我正在用x10语言做我的项目。如果你能帮助我与x10代码,这将是伟大的。但是,即使在Java中,您的支持也将受到感谢。
保存
DataOutputStream os = new DataOutputStream(new FileOutputStream("file.dat"));
os.writeInt(1234); // Write as many ints as you need
os.writeInt(2345);
加载DataInputStream is = new DataInputStream(new FileInputStream("file.dat"));
int val = is.readInt(); // read the ints
int val2 = is.readInt();
保存数据结构数组的示例
这个例子没有创建固定长度的记录,但可能有用:
假设你有一个数据结构
class Record {
public int id;
public String name;
}
您可以这样保存记录数组:
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();
}
然后像这样加载它们:
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;
}