XXXbuffer与SeekableByteChannel的配合方法

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;

public class Easy {

	public static void main(String[] args) {
		ByteBuffer buffer = ByteBuffer.allocate(24);//定义缓冲区大小
		//对缓冲区进行写入
		System.out.println(buffer.position());//看内部指针的
		buffer.putInt(23);//写入数字23 内部指针移动4个内存字节 该数字在int内的区间内定值无论值 
                     //是多少,指针都是移动4个字节,也就是说buffer分配了4个字节的内存给写入的值 
                          
		System.out.println(buffer.position());//4 证明putInt()方法使内部指针移动4个位置 
		buffer.putChar('b');//写入字符'b' 内部指针移动2个字节 分配了两个字节的内存
		System.out.println(buffer.position());//6
		buffer.putInt(45);//写入数字45 测试 
		System.out.println(buffer.position());//10
		System.out.println(buffer.getInt());//打印0 因为是在内部指针在10的相对位置去获取int 
                                            //类型的元素所以失败了
		//对buffer缓冲区读取
		buffer.rewind();//将内部指针置0
		System.out.println(buffer.position());//0
		System.out.println(buffer.getInt());//23 在0的绝对位置下获取数据
		System.out.println(buffer.getChar(4));//b 同理 但是想要读取字符'b'必须在位置4才能正 
                                              //确的读取数据

		System.out.println(buffer.getInt(6));//45 在指针位置为6时读取数据正确 
		buffer.rewind();//将内部指针置0 方便后面操作方便安全

		//将文本文件数据复制到缓冲区
		Path path1 = Paths.get("D:\\music\\emq\\emm.txt");//使用get方法创建Path的快捷方式

		try(SeekableByteChannel emmFile = 
				Files.newByteChannel(path1,
				StandardOpenOption.CREATE,//该配置是 若文件不存在时自己创建一个文件
				StandardOpenOption.READ,
				StandardOpenOption.WRITE)//配置字节通道 打开方式既可读又可写
			)
		{	//写入
			System.out.println(emmFile.position());//0
			emmFile.write(buffer);//SeekableByteChannel的write需要一个XXXBuffer的缓冲区存储 
                                  //文本的数据
			System.out.println(emmFile.position());//为buffer缓冲区分配了20个字节的内存

			//读取
			ByteBuffer buffer2 = ByteBuffer.allocate(40);//新建一个字节缓冲区
			emmFile.position(0);//将emmFile的内部指针置0方便操作
			emmFile.read(buffer2);//文本的字节复制到buffer2的缓冲区
			buffer2.rewind();//将buffer2的内部指针置0 方便读取

			//第一种按顺序读取
			System.out.println("int :"+ buffer2.getInt());//23
			System.out.println("char :"+ buffer2.getChar());//b
			System.out.println("int :"+ buffer2.getInt());//45

			//第二种按指定下标位置读取
			System.out.println("int :"+ buffer2.getInt(6));//45
			System.out.println("char :"+ buffer2.getChar(4));//b
			System.out.println("int :"+ buffer2.getInt(0));//23
			
		}catch(IOException e){
			e.printStackTrace();
		}
	}		
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值