nio的作用:提高速度
包括FileChannel,相当于数据的存储;
ByteBuffer,相当于每次读取的一部分数据存储器。
package star20110531;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class GetChannel {
private static final int BSIZE = 1024;
public static void main(String[] args) throws IOException {
//FileOutputStream产生一个FileChannel通道
FileChannel fileChannel = new FileOutputStream("B05\\star20110531\\test.txt").getChannel();
//ByteBuffer相当于往这个通道提供的一份份数据
//wrap()是将字节数组放到ByteBuffer这个缓冲区中
fileChannel.write(ByteBuffer.wrap("star very good".getBytes()));
fileChannel.close();
//add to the end of the file
fileChannel = new RandomAccessFile("B05\\star20110531\\test.txt","rw").getChannel();
//移动位置
fileChannel.position(fileChannel.size());
fileChannel.write(ByteBuffer.wrap("bobo is good too".getBytes()));
fileChannel.close();
//读取数据
fileChannel = new FileInputStream("B05\\star20110531\\test.txt").getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(BSIZE);
System.out.println(byteBuffer);
//上面的syso结果:java.nio.HeapByteBuffer[pos=0 lim=1024 cap=1024]
fileChannel.read(byteBuffer);
byteBuffer.flip();
//flip()方法首先对当前位置设置限制,然后将该位置设置为零。如果已定义了标记,则丢弃该标记。
// System.out.println(byteBuffer.flip());
//上面的syso结果:java.nio.HeapByteBuffer[pos=0 lim=0 cap=1024]
while(byteBuffer.hasRemaining()){
System.out.print(byteBuffer.remaining()+"->");
System.out.print((char)byteBuffer.get()+"\t");
}
}
}