NIO是Java New IO 的简称,是在Java 4 中提供的新特性 。NIO为所有的原始类型提供缓存支持、字符集编码解码解决方案。支持锁和内存映射文件的文件访问接口,提供多路(non-bloking) 非阻塞式的高伸缩性网络I/O 。
10.6.1 使用Buffer
Buffer是一个包装了基本数据元素数组的对象,是 NIO 数据读或写的中转地。Buffer有四个基本属性,分别是:
1、capacity :buffer能够容纳的最大元素数目;
2、limit buffer:buffer中有效位置数目;
3、position :下一个读或者写的位置;
4、mark: 用于记忆的标志位。
Buffer 常用的方法有:
1、flip():写模式转换成读模式;flip()方法会改变limit属性,将limit属性从capacity设置为当前position。两次调用buffer的flip方法,将使得position和limit属性都为0。
2、rewind() :将position 重置为 0 ,一般用于重复读;
3、clear() :清空buffer ,准备再次被写入;
4、compact(): 将未读取的数据拷贝到 buffer 的头部位;
5、mark() :mark标记一个位置;
6、 reset():重置位置。
下面就是一个使用Buffer实现文件拷贝的例子,代码如清单10-14所示。
清单10-14
|
package com.javapp.ch10; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class BufferTest { @SuppressWarnings("resource") public static void main(String[] args) throws Exception { String infile = "D:\\javadir\\javaapp\\src\\com\\javapp\\ch10\\BufferTest.java"; String outfile = "D:\\test.txt"; // 获取输入输出通道 FileChannel fcin = new FileInputStream(infile).getChannel(); FileChannel fcout = new FileOutputStream(outfile).getChannel(); // 创建缓冲区 ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { buffer.clear(); // 从输入通道中将数据读到缓冲区 int r = fcin.read(buffer); //如果该通道已到达流的末尾,则返回-1 if (r == -1) { break; } buffer.flip();//写模式转换成读模式 // 从输出通道中将数据写入缓冲区 fcout.write(buffer); } } } |
在上面程序中,用ByteBuffer 实现文件的拷贝,Buffer 常见类型有 ByteBuffer 、 MappedByteBuffer 、CharBuffer、DoubleBuffer 、FloatBuffer、IntBuffer、LongBuffer 、ShortBuffer 。
2684



被折叠的 条评论
为什么被折叠?



