我需要将固定大小的记录存储到文件中。每条记录有两个ID,每个ID共享4bytes。我正在用x10语言做我的项目。如果你可以帮助我使用x10代码,那就太好了。 但即使在Java中,您的支持也会受到赞赏。
答案 0 :(得分:1)
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;
}