使用Buffer
来源:互联网 发布:淘宝卖家不同意退货 编辑:程序博客网 时间:2024/06/14 19:33
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 。
- 使用Buffer
- Buffer使用
- google proto buffer使用
- protocol buffer简单使用
- google proto buffer使用
- 查看buffer pool使用
- buffer object 的使用
- Protocol buffer使用
- protocol buffer使用举例
- Protoc buffer的使用
- Protocol Buffer使用
- 为什么使用Protocol Buffer
- protocol buffer 使用
- Protocol Buffer使用简介
- Protocol Buffer使用简介
- 使用buffer拷贝文件
- protocol buffer的使用
- opengl stencil buffer使用
- 2013年6月20日
- sql级联删除
- IOS字符串模糊查找算法
- 转载文章:Windows Azure 基础结构服务上的 Microsoft Dynamics NAV 和 Microsoft Dynamics GP!
- 文件锁
- 使用Buffer
- NET使用NPOI组件将数据导出Excel
- Java 7 二进制字面值
- 探讨C++ 变量生命周期、栈分配方式、类内存布局、Debug和Release程序的区别(一)
- 一个Linux下C线程池的实现
- 自学C语言练习1
- mysql 多列连接
- 探讨C++ 变量生命周期、栈分配方式、类内存布局、Debug和Release程序的区别(二)
- 调用其它app中的Service