I am trying to write a large Long Array of size 400000000 into a file and then read it back. What code I am using is following:
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;
}
}
However, this code is giving error that write and read array are not same. Can anybody help me why is this happening ?
I think your
getMbb()method is broken. Every time you remap the chunk of the file in memory, you map tochannel.size(). That only works while you are creating the file, but not when you are reading it. When you are reading the file, you map the “region” of the file that come after the end of the file, and that has random contents.You will have to fix the remapping code to keep track of where in the file you already are.