用java将8字节长的记录写入文件
我需要将固定大小的记录存储到文件中。每个记录有两个ID,每个ID共享4字节。我正在用x10语言做我的项目。如果你能帮助我使用x10代码,那就太好了。 但即使是在Java中,您的支持也将受到感谢。 加载 保存数据结构数组的示例 此示例不创建固定长度的记录,但可能有用: 假设您有一个数据结构用java将8字节长的记录写入文件,java,fixed-length-record,x10-language,Java,Fixed Length Record,X10 Language,我需要将固定大小的记录存储到文件中。每个记录有两个ID,每个ID共享4字节。我正在用x10语言做我的项目。如果你能帮助我使用x10代码,那就太好了。 但即使是在Java中,您的支持也将受到感谢。 加载 保存数据结构数组的示例 此示例不创建固定长度的记录,但可能有用: 假设您有一个数据结构 class Record { public int id; public String name; } 您可以保存一组记录,如下所示: void saveRecords(Record[] re
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;
}
Record[]loadRecords()引发IOException{
DataInputStream是=新的DataInputStream(新的FileInputStream(“file.dat”);
int recordCount=is.readInt();//读取记录数
记录[]ret=新记录[recordCount];//分配返回数组
for(int i=0;i
如何确保os.writeInt()只使用四个字节?如果我需要将文本存储为8个字节,是否也有办法做到这一点?根据规范,它将始终保存4个字节。请参阅将int作为4个字节写入底层输出流,高字节优先。
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;
}