nick bijmoer nick bijmoer - 8 months ago 29
Java Question

Read memory mapped file

I have to read a memory mapped file, writing seems to work but I don't know how to properly read it. This is how I write the file:

public static void writeMapped(ArrayList<Edge> edges) throws FileNotFoundException, IOException{
// Create file object
File file = new File("data.txt");

//Delete the file; we will create a new file
file.delete();

// Get file channel in readonly mode
FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();
// Get direct byte buffer access using channel.map() operation
// 7 values * 8 bytes(double = 8byte)
MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, (7*8)*edges.size());

//Write the content using put methods
for(Edge e : edges){
buffer.putDouble(e.X1);
buffer.putDouble(e.Y1);
buffer.putDouble(e.X2);
buffer.putDouble(e.Y2);
buffer.putDouble(e.color.getHue());
}

System.out.print("mapped done!");
}


I have to read the file and create the exact same arraylist as I had when I wrote the file.

Answer Source

It would be something along those lines, though it may need some polishing :

File file =  new File("data.txt");

FileChannel fileChannel = new RandomAccessFile(file, "r").getChannel();

MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());

List<Edge> edges= new ArrayList<Edge>();

while(buffer.hasRemaining())
{
    Edge e = new Edge();
    e.X1 = buffer.getDouble();
    e.Y1 = buffer.getDouble();
    e.X2 = buffer.getDouble();
    e.Y2 = buffer.getDouble();
    // here you will need to set the color Object first !!
    // e.color.setHue(buffer.getDouble());

    edges.add(e);

}