读取内存映射文件

时间:2015-12-08 16:49:53

标签: java file memory

我必须阅读一个内存映射文件,写作似乎有效,但我不知道如何正确阅读它。这就是我写文件的方式:

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!");
 }

我必须阅读文件并创建与编写文件时完全相同的arraylist。

1 个答案:

答案 0 :(得分:1)

虽然可能需要进行一些抛光,但这可能会有所不同:

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

}