读书人

【Java NIO】内存储器映射文件

发布时间: 2012-09-10 11:02:32 作者: rapoo

【Java NIO】内存映射文件

java.nio包包含对下列特性的支持:

1.字符集编码器和解码器

2.非阻塞的I/O

3.内存映射文件

4.文件加锁机制

?

?

内存映射文件

?

file-mapping model

?

?

缓冲区数据结构——Buffer

?

?

在使用内存映射时,我们创建了单一的缓冲区横跨整个文件或部分文件区域。

类继承结构如下:
【Java NIO】内存储器映射文件

上面Buffer都没有提供构造,可以通过如下方法来获得Buffer实例:

static xxxBuffer allocate(int capacity)

?

Channel

Channel类似传统io里的流,但与流不同在于:

1.channel可以直接将指定文件的部分或者全部映射成Buffer

2.程序通过buffer读写channel中的数据。

比如想从channel中读取一些数据,首先会将这些数据读入buffer,然后程序再从buffer中读。写也一样要通过buffer往channel中写数据。

?

Channel的继承结构:

【Java NIO】内存储器映射文件

?

?

文件通道

?

打开Channel

XxxChannel = XxxInputStream / XxxOutputStream .getChannel()

?

FileChannel常用方法

MapperByteBuffer map(FileChannel.MapMode mode, long position, long size);

将channel中部分or全部数据映射成buffer

?

通过Channel 和 Buffer从文件中读数据

FileInputStream input = new FileInputStream(fileName);FileChannel channel = input.getChannel();MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY/READ_WRITE/PRIVATE,? ? long position, long size);//将文件的一个区域映射到内存中buffer.get();//对buffer的读操作

?

通过Buffer 和 Channel向文件中写数据

FileOutputStream output = new FileOutputStream(fileName);FileChannel channel = output.getChannel();MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY/READ_WRITE/PRIVATE,? ? long position, long size);//将文件的一个区域映射到内存中buffer.put();//对buffer的写操作

?

FileChannel的内部类里定义了文件映射模式

public static class MapMode {/** * Mode for a read-only mapping. */public static final MapMode READ_ONLY    = new MapMode("READ_ONLY");/** * Mode for a read/write mapping. */public static final MapMode READ_WRITE    = new MapMode("READ_WRITE");/** * Mode for a private (copy-on-write) mapping. */public static final MapMode PRIVATE    = new MapMode("PRIVATE");private final String name;private MapMode(String name) {    this.name = name;}/** * Returns a string describing this file-mapping mode. * * @return  A descriptive string */public String toString() {    return name;}    }

?

实例1:文件拷贝

?

?

实例2:文件追加内容

?

通道只能在字节缓冲区上操作

?

?

socket通道

?

?

?

读书人网 >编程

热点推荐