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 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");
		}
		
	}
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值