您的位置:首页 > 编程语言 > Java开发

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
*///:~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: