ByteBufferTest

package io;

import java.io.*;

import java.nio.*;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class BufferTest {

/**
* @param args
*/
public static void main(String[] args)
{
try {
FileChannel fco = new FileOutputStream("E:\\ApiProjectTemp\\data.txt")
.getChannel();
ByteBuffer bb = ByteBuffer.wrap("some text".getBytes("GBK"));
fco.write(bb);
fco.close();

fco = new RandomAccessFile("E:\\ApiProjectTemp\\data.txt","rw").getChannel();
System.out.println("此通道的文件位置:" + fco.position());
fco.position(fco.size());
System.out.println("此通道的文件位置:" + fco.position());
// 在文件末尾写入字节
fco.write(ByteBuffer.wrap("Some more".getBytes()));
fco.close();

FileChannel fci = new FileInputStream("E:\\ApiProjectTemp\\data.txt").getChannel();
ByteBuffer bbo = ByteBuffer.allocate(1024); //1024 * 1024
System.out.println(bbo.limit());//当还没读取的时候极限和容量是相等的
// 将文件内容读到指定的缓冲区中
fci.read(bbo);
bbo.flip();//此行语句一定要有 ,方法,把position和limit移动到要读取的数据两端 。
/*ByteBuffer实际上是一块连续的内容 可以理解成一个byte数组
* 读:读position和limit之间的数据,这儿要注意,不是读取0到capacity之间数据,读前一般会执行。
* position:读/写的开始位置
limit:读/写的结束位置
capacity:数组大小
clear():首先把极限设置为容量,再者就是需要把位置设置为0;
flip():把极限设置为位置区,再者就是需要把位置设置为0;
rewind():不改变极限,不过还是需要把位置设置为0。
*/
System.out.println(bbo.capacity());//容量
System.out.println(bbo.limit());//极限改变了为实际的字节总长度
System.out.println(bbo.position());
System.out.println(bbo.limit());
//System.out.println(bbo.limit(2));输出为so
while(bbo.hasRemaining())
{
System.out.print((char)bbo.get());
}
System.out.println();
System.out.println("-------------------");
bbo.rewind();//准备重读
while(bbo.hasRemaining())
{
System.out.print((char)bbo.get());
}
System.out.println();
System.out.println("-------------------");
bbo.rewind();//准备重读
Charset chrst = Charset.forName("GBK");
CharBuffer charReader = chrst.decode(bbo);
System.out.println(charReader.toString());
fci.close();
} catch (Exception e)
{
e.printStackTrace();
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值