Java 新I/O 通道和缓冲器

来源:互联网 发布:英文阅读书籍软件 编辑:程序博客网 时间:2024/05/16 15:04
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*///:~

0 0