Java 读取内存映射文件
我必须读一个内存映射文件,写似乎可以,但我不知道如何正确地读取它。以下是我编写文件的方式:Java 读取内存映射文件,java,file,memory,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 creat
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!");
}
publicstaticvoidwritemapped(arraylistedges)抛出FileNotFoundException、IOException{
//创建文件对象
File File=新文件(“data.txt”);
//删除该文件;我们将创建一个新文件
delete();
//以只读模式获取文件通道
FileChannel FileChannel=新的随机访问文件(文件“rw”).getChannel();
//使用channel.map()操作获取直接字节缓冲区访问
//7个值*8个字节(双精度=8个字节)
MappedByteBuffer buffer=fileChannel.map(fileChannel.MapMode.READ_WRITE,0,(7*8)*edges.size());
//使用put方法编写内容
用于(边e:边){
buffer.putDouble(e.X1);
缓冲区。putDouble(e.Y1);
buffer.putDouble(e.X2);
buffer.putDouble(e.Y2);
puttouble(e.color.getHue());
}
System.out.print(“映射完成!”);
}
我必须阅读该文件并创建与我编写该文件时完全相同的arraylist。这将是类似的内容,尽管可能需要一些润色:
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);
}
File File=new文件(“data.txt”);
FileChannel FileChannel=new RandomAccessFile(文件“r”).getChannel();
MappedByteBuffer buffer=fileChannel.map(fileChannel.MapMode.READ_ONLY,0,fileChannel.size());
列表边=新的ArrayList();
while(buffer.haslaining())
{
边e=新边();
e、 X1=缓冲区.getDouble();
e、 Y1=buffer.getDouble();
e、 X2=buffer.getDouble();
e、 Y2=buffer.getDouble();
//在这里,您需要先设置颜色对象!!
//e.color.setHue(buffer.getDouble());
加入(e);
}
这是我们目前正在教的学生的家庭作业。