Java:将多个int数组写入二进制文件以进行反向索引
我目前正在用Java做一个反向索引项目,该项目将int数组写入一个二进制文件,然后保存偏移量以及每个数组要读取的字节数,以便以后可以将其读回内存。我怎样才能做到这一点?我以前从未处理过二进制文件,所以我不知道从哪里开始。您可以使用编写原始数据和读取原始数据。这保证了数据不会以文本形式写入 这两个类基本上对每个基本类型都有一个重载,例如Java:将多个int数组写入二进制文件以进行反向索引,java,arrays,Java,Arrays,我目前正在用Java做一个反向索引项目,该项目将int数组写入一个二进制文件,然后保存偏移量以及每个数组要读取的字节数,以便以后可以将其读回内存。我怎样才能做到这一点?我以前从未处理过二进制文件,所以我不知道从哪里开始。您可以使用编写原始数据和读取原始数据。这保证了数据不会以文本形式写入 这两个类基本上对每个基本类型都有一个重载,例如int,float,char,等等,这使得使用它们非常简单。要写入和读取ints,您可以使用writeInt()和readInt()方法 例如,您可以这样编写int
int
,float
,char
,等等,这使得使用它们非常简单。要写入和读取int
s,您可以使用writeInt()
和readInt()
方法
例如,您可以这样编写int[]
:
int[] myArray = ...;
DataOutputStream os = new DataOutputStream(new FileOutputStream("C:\\somefile.dat"));
//write the length first so that you can later know how many ints to read
os.writeInt(myArray.length);
for (int i =0 ; i < myArray.length; ++i){
os.writeInt(myArray[i]);
}
os.close();
int[]myArray=。。。;
DataOutputStream os=新的DataOutputStream(新文件输出流(“C:\\somefile.dat”);
//先写下长度,以便以后知道要读取多少整数
os.writeInt(myArray.length);
对于(int i=0;i
要重新阅读:
DataInputStream is = new DataInputStream(new FileInputStream("C:\\somefile.dat"));
int size = is.readInt(); //read the size which is the first int
int[] myArray = new int[size]; //use it to reconstruct the array
for (int i = 0; i < size; ++i){
myArray[i] = is.readInt(); //read all the remaining ints
}
is.close();
DataInputStream is=newdatainputstream(newfileinputstream(“C:\\somefile.dat”);
int size=is.readInt()//读取第一个整数的大小
int[]myArray=新的int[size]//使用它重建阵列
对于(int i=0;i
请注意,这些示例没有异常处理,如果您想确保程序在文件不存在或数据损坏的情况下不会崩溃,这一点很重要。首先阅读文档
DataOutputStream
或RandomAccesFile
立即浮现在脑海中。