thinking in java学习之nio-bytebuffer4

1、bytebuffer有四个属性



1、position :

当前读取的位置;调用position()时获取;调用get()方法时指向读取位置的下一位;调用put()时指向当前写入的位置的下一位;

2、mark :  

调用mark()时标记当前读取的位置值;设置为负值时废弃次标记;

3、limit:

读取的界限;limit<=capacity;

4、capacity :

容量;bytebuffer.allocate(capacity);

2、写入完准备读取之前,必须调用flip()方法;

flip方法源码:
public final Buffer flip() {
	limit = position;
	position = 0;
	mark = -1;
	return this;
    }


3、重复使用时,必须在下一次调用之前调用clear();

clear方法源码:

public final Buffer clear() {
	position = 0;
	limit = capacity;
	mark = -1;
	return this;
}

4、reset与rewind

reset将position设置为mark的值
public final Buffer reset() {
        int m = mark;
        if (m < 0)
            throw new InvalidMarkException();
        position = m;
        return this;
    }
rewind将position设置为0
  public final Buffer rewind() {
        position = 0;
        mark = -1;
        return this;
    }



4、复制文件示例

// 源文件
				ch3 = new FileInputStream(filePath).getChannel();
				// 目标文件
				ch4 = new FileOutputStream("E:/1s.txt").getChannel();
//				int size = new Long(ch3.size()).intValue();
				int bufferSize = 10;
				ByteBuffer bb = ByteBuffer.allocate(bufferSize);
				StringBuilder content = new StringBuilder();
				while (ch3.read(bb) != -1) {
					bb.flip();
					ch4.write(bb);
					bb.clear();
				}


5、直接bytebuffer转字符串输出

Charset.forName(System.getProperty("file.encoding"))
				.decode(bytebuffer); 

6、bytebuffer的视图


ByteBuffer bb = ByteBuffer
				.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, 'a' });
		try {
			// set position 0
			bb.rewind();
			// print as byte(1)
			while (bb.hasRemaining()) {
				System.out.print(bb.position() + "=" + bb.get() + "  ");
			}
			System.out.println();
			// print as char(2)
			CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer();
			while (cb.hasRemaining()) {
				System.out.print(cb.position() + "=" + cb.get() + "  ");
			}
			System.out.println();
			// print as float(4)
			FloatBuffer fb = ((ByteBuffer) bb.rewind()).asFloatBuffer();
			while (fb.hasRemaining()) {
				System.out.print(fb.position() + "=" + fb.get() + "  ");
			}
			System.out.println();
			// print as int (4)
			IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer();
			while (ib.hasRemaining()) {
				System.out.print(ib.position() + "=" + ib.get() + "  ");
			}
			System.out.println();
			// print as long
			LongBuffer lb = ((ByteBuffer) bb.rewind()).asLongBuffer();
			while (lb.hasRemaining()) {
				System.out.print(lb.position() + "=" + lb.get() + "  ");
			}
			System.out.println();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值