繁体   English   中英

读取内存映射文件

[英]Read memory mapped 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!");
 }

我必须读取文件并创建与我编写文件时完全相同的数组列表。

这将是沿着这些路线的东西,尽管它可能需要一些改进:

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM