nick bijmoer nick bijmoer - 1 year ago 46
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

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

//Write the content using put methods
for(Edge e : edges){

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 =, 0, fileChannel.size());

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

    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());


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download