所谓的NIO,是new io的缩写,它提供了buffer的功能来提交io的性能。jdk从1.4之后开始提供相关操作。
基本结构:Buffer抽象类的一系列子类实现,其中BooleanBuffer不存在,也没必要缓冲。具体如下:,,,,,
Buffer有四个基本属性: 1、capacity 容量,buffer能够容纳的最大元素数目,在Buffer创建时设定并不能更改 2、limit buffer中有效位置数目 3、position 下一个读或者写的位置 4、mark 用于记忆的标志位,配合reset()使用,初始值未设定,调用mark后将当前position设为值 四者关系:0 <= mark <= position <= limit <= capacity
同时针对各中数据结构,提供了通道(channel)的概念,可以针对该数据结构进行双向操作。
例1:ByteBuffer使用
- ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
- byteBuffer.put("hello wolrd".getBytes());
- System.out.println(byteBuffer.position());
- System.out.println(byteBuffer.capacity());
- System.out.println(byteBuffer.limit());
例2:文件内容拷贝
- String infile = "C:\\from.txt";
- String outfile = "C:\\to.txt";
- // 获取源文件和目标文件的输入输出流
- FileInputStream fin = new FileInputStream(infile);
- FileOutputStream fout = new FileOutputStream(outfile);
- // 获取输入输出通道
- FileChannel fcin = fin.getChannel();
- FileChannel fcout = fout.getChannel();
- // 创建缓冲区
- ByteBuffer buffer = ByteBuffer.allocate(1024);
- while (true) {
- // clear方法重设缓冲区,使它可以接受读入的数据
- buffer.clear();
- // 从输入通道中将数据读到缓冲区
- int r = fcin.read(buffer);
- // read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
- if (r == -1) {
- break;
- }
- // flip方法让缓冲区可以将新读入的数据写入另一个通道
- buffer.flip();
- // 从输出通道中将数据写入缓冲区
- fcout.write(buffer);
- }
更多例子,参考: