Java 新I/O 通道和缓冲器
2016-05-09 16:12
197 查看
package io; import java.nio.*; import java.nio.channels.*; import java.io.*; /* * 三种类型的流用以产生可写的,可读的,可读可写的通道。 * getChannel()将会产生一个FileChannel通道,可以向他传送用于读写的ByteBuffer,并且可以锁定文件的某些区域用于独占式访问。 * 将字节放于ByteBuffer中的方法用put方法,也可以用wrap方法将以存在的字节数组包装到ByteBuffer中。一旦如此,就不会复制底层的数组 * 而是把它作为所产生ByteBuffer的存储器,称之为数组支持的ByteBuffer。 * 一旦调用read()来告知FileChannel向ByteBuffer存储字节,就必须调用缓冲器上的flip(),让他做好别人读取字节的准备。*/ public class GetChannel { private static final int BSIZE = 1024; @SuppressWarnings("resource") public static void main(String[] args) throws Exception { // Write a file: @SuppressWarnings("resource") FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text ".getBytes())); fc.close(); // Add to the end of the file: fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); // Move to the end fc.write(ByteBuffer.wrap("Some more".getBytes())); fc.close(); // Read the file: fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while(buff.hasRemaining()) System.out.print((char)buff.get()); } } /* Output: Some text Some more *///:~
相关文章推荐
- 九龙_Java开发之路_1
- Java基础9
- Java异常
- Java设计模式 · 观察者模式
- java动态绑定在属性和方法上的不同
- Java Reflection(十二):动态类加载与重载
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- Spring中depends-on的作用是什么?
- 深入Java集合学习系列:ArrayList的实现原理
- SpringMVC接收checkbox传值
- spring整合消息队列rabbitmq
- 在Eclipse中导入android项目,默认以Google API运行的解决办法
- java 用两个栈实现队列
- (2.1.19.5)深入理解Java:注解(Annotation)--注解处理器
- java验证码组件Jcaptcha
- SpringMVC简介与配置
- java web 生成图片验证码的功能实现
- java反射详解
- 使用Eclipse构建Maven项目(step-by-step)
- 跟我学分布式-Dubbo整合spring