【Java NIO】内存映射文件

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

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

2.非阻塞的I/O

3.内存映射文件

4.文件加锁机制

 

 

内存映射文件

 

file-mapping model

 

 

缓冲区数据结构——Buffer

 

 

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

类继承结构如下:

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

static xxxBuffer allocate(int capacity)

 

Channel

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

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

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

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

 

Channel的继承结构:

 

 

文件通道

 

打开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通道

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值