-1

我需要将固定大小的记录存储到文件中。每条记录有两个 ID,每个 ID 共享 4 个字节。我正在用 x10 语言做我的项目。如果你能用 x10 代码帮助我,那就太好了。但即使在 Java 中,您的支持也将不胜感激。

4

1 回答 1

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;
}
于 2015-07-24T16:51:52.913 回答