我正在尝试将大小为 400000000 的大型长数组写入文件,然后将其读回。我正在使用的代码如下:
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
import java.io.RandomAccessFile ;
import java.util.* ;
class Checks {
public static FileChannel channel;
public static MappedByteBuffer mbb;
public static void main(String[] args){
try{
long k[] = new long[400000000] ;
for(int i = 0 ; i < 400000000 ; i++){
k[i] = i ;
}
channel = new RandomAccessFile("abc.dat", "rw").getChannel();
mbb = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1 << 24);
mbb.order(ByteOrder.nativeOrder());
for(int i = 0 ; i < 400000000 ;i++ ){
getMbb().putLong(k[i]);
}
channel.close();
long ks[] = new long[400000000] ;
channel = new RandomAccessFile("abc.dat", "rw").getChannel();
mbb = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1 << 24);
mbb.order(ByteOrder.nativeOrder());
for(int r = 0 ; r < 400000000; r++){
ks[r] = getMbb().getLong();
}
for(int r = 0 ; r < 400000000; r++){
if(k[r] != ks[r]){
System.out.println("Error at " + r);
break ;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static ByteBuffer getMbb() throws IOException {
if (mbb.remaining() <= 0) {
mbb = channel.map(FileChannel.MapMode.READ_WRITE, channel.size(), 1 << 24);
mbb.order(ByteOrder.nativeOrder());
}
return mbb;
}
}
但是,此代码给出了写入和读取数组不相同的错误。任何人都可以帮助我为什么会发生这种情况?