JAVA映射文件到内存,java之内存映射文件

  • Post author:
  • Post category:java


大多数操作系统都可以利用虚拟内存实现来将一个文件或者文件的一部分“映射”到内存中。然后这个文件就可以当作内存数组一样访问,这比传统的文件操作要快很多。

在java中,提供了FileChannel类来实现文件的内存映射。使用FileChannel大致可以分为下面三个步骤:

调用FileChannel.open()方法,获取一个FileChannel的引用

调用FileChannel的map方法,获取到一个ByteBuffer.

操作ByteBuffer,获取想要的数据

下面是一个简单的演示demo:

Path path = Paths.get(“d:\\hello.txt”);

FileChannel fc = FileChannel.open(path, StandardOpenOption.READ);

long length = fc.size();

ByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, length);

int size = buffer.limit();

byte[] data = new byte[size];

buffer.get(data);

String msg = new String(data, 0, data.length, Charset.forName(“utf-8”));

System.out.println(msg);

有几个参数还说有有必要说明一下:

open(Path path,OpenOpiton opitions):第一个参数表示文件的path路径,第二个参数表示打开的可选项,一般使用StandardOpenOption中的枚举值WRITE、APPEND、TRUNCATE_EXISTING、CREATE、READ等值。

map(FileChannel.MapMode mode, long position, long size):modes表示文件映射区域的映射模式,有三个属性FileChannel.MapMode.READ_ONLY表示所产生的缓冲区是只读的;FileChannel.MapMode.READ_WRITE表示所产生的缓冲区是可写的,任何修改都会在某个时刻写回到文件中;FileChannel.MapMode.PRIVATE表示所产生的缓冲区是可写的,任何对于缓冲区的修改都不会传播到文件中。