首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java.nio的学习记要

2012-12-22 
java.nio的学习记录nio的作用:提高速度?? ? ? ?包括FileChannel,相当于数据的存储;?? ? ?ByteBuffer,相当

java.nio的学习记录

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 filefileChannel = 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");}}}
?

热点排行