byteBuffer_bytebuffer.wrap

byteBuffer_bytebuffer.wrap引言在nio中,流的读取和写入都是依赖buffer的。jdk在nio包中提供了ByteBuffer、CharBuffer、ShortBuffer、LongBuffer、DoubleBuffer、FloatBuffer等。6中类型的buffer还分为两种实现,缓存在jvm堆中和缓存在直接内存中。Buffer主要属性//Invariants:mark<=position&lt…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

引言

在nio中,流的读取和写入都是依赖buffer的。jdk在nio包中提供了ByteBuffer、CharBuffer、ShortBuffer、LongBuffer、DoubleBuffer、FloatBuffer等。 6中类型的buffer还分为两种实现,缓存在jvm堆中和缓存在直接内存中。

Buffer

主要属性

// Invariants: mark <= position <= limit <= capacity
    private int mark = -1;
    private int position = 0;
    private int limit;
    private int capacity;

    // Used only by direct buffers
    // NOTE: hoisted here for speed in JNI GetDirectBufferAddress
    long address;

主要方法

这些方法是用来控制buffer的读写。
jdk提供的buffer只有一个position指针,读和写都是从position的位置开始操作。
代码的流程常常是这样的:
buffer.put(1);
buffer.flip();
buffer.get();
用于多次读取操作

public final Buffer mark() { 
   
        mark = position;
        return this;
    }

public final Buffer reset() { 
   
        int m = mark;
        if (m < 0)
            throw new InvalidMarkException();
        position = m;
        return this;
    }

假装清空

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

翻转指针

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

剩余容量

public final int remaining() { 
   
        return limit - position;
    }

获取读写指针的方法

final int nextGetIndex() { 
                             // package-private
        if (position >= limit)
            throw new BufferUnderflowException();
        return position++;
    }

final int nextPutIndex() { 
                             // package-private
        if (position >= limit)
            throw new BufferOverflowException();
        return position++;
    }

ByteBuffer

主要属性

// byte数组
final byte[] hb;                  // Non-null only for heap buffers
// offset 在派生的时候有用
    final int offset;

实例化方法

创建指定容量的heapBuffer和directBuffer

public static ByteBuffer allocate(int capacity) { 
   
        if (capacity < 0)
            throw new IllegalArgumentException();
        return new HeapByteBuffer(capacity, capacity);
    }

public static ByteBuffer allocateDirect(int capacity) { 
   
        return new DirectByteBuffer(capacity);
    }

通过数组创建ByteBuffer

public static ByteBuffer wrap(byte[] array,
                                    int offset, int length)
    { 
   
        try { 
   
            return new HeapByteBuffer(array, offset, length);
        } catch (IllegalArgumentException x) { 
   
            throw new IndexOutOfBoundsException();
        }
    }

put和get方法

public ByteBuffer put(byte x) { 
   
		
		// 获取put的指针 
        hb[ix(nextPutIndex())] = x;
        return this;
    }

public byte get() { 
   
		// 获取get的指针
        return hb[ix(nextGetIndex())];
    }

protected int ix(int i) { 
   
        return i + offset;
    }

派生ByteBuffer
slice创建的Buffer,读写都是在数组的子序列上进行。依赖于Buffer的当前索引

// 共享数组,position=0 mark=-1 limit=cap,
public ByteBuffer slice() { 
   
        return new HeapByteBuffer(hb,
                                        -1,
                                        0,
                                        this.remaining(),
                                        this.remaining(),
                                        this.position() + offset);
    }

复制一个对象,共享数组,拥有相同数值的mark、position、limit、capacity和offset

public ByteBuffer duplicate() { 
   
        return new HeapByteBuffer(hb,
                                        this.markValue(),
                                        this.position(),
                                        this.limit(),
                                        this.capacity(),
                                        offset);
    }

把已经在本buffer写的元素移动到0位置,position定位到剩余容量起点,limit限制为capacity

public ByteBuffer compact() { 
   
        System.arraycopy(hb, ix(position()), hb, ix(0), remaining());
        position(remaining());
        limit(capacity());
        discardMark();
        return this;
    }

常用代码段

// 拷贝文件
public void copyFile(String copyFrom,String copyTo){ 
   
	File file = new File(copyFrom);
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        FileChannel channel = randomAccessFile.getChannel();

        File outFile = new File(copyTo);
        RandomAccessFile outRAF = new RandomAccessFile(outFile, "rw");
        FileChannel outChannel = outRAF.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (channel.read(byteBuffer) > 0){ 
   
            while (byteBuffer.hasRemaining()){ 
   
                byteBuffer.flip();
                outChannel.write(byteBuffer);
            }
        }
}

// 从网络中读取文件
public void readNetworkFile(){ 
   
		File outFile = new File("d://20200418220925641.png");
        RandomAccessFile outRAF = new RandomAccessFile(outFile, "rw");
        FileChannel outChannel = outRAF.getChannel();
        // get stream from net
        InputStream inputStream = new URL("https://img-blog.csdnimg.cn/20200418220925641.png").openConnection()
            .getInputStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        byte[] cache = new byte[2 * 1024];
        ByteBuffer wrap = ByteBuffer.wrap(cache);
        int len;
        while ((len = bufferedInputStream.read(cache)) > 0){ 
   
            wrap.position(0);
            wrap.limit(len);
            outChannel.write(wrap);
        }
}

public void writeMsgToClient(){ 
   
		ServerSocket serverSocket = new ServerSocket(9988);
		// bad case
        Socket accept = serverSocket.accept();
        SocketChannel channel = accept.getChannel();
        // do business logic and get a byte array
        byte[] rlt = "businessLogicRlt".getBytes();
        ByteBuffer wrap = ByteBuffer.wrap(rlt, 0, rlt.length);
        channel.write(wrap);
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/186804.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • awk教程「建议收藏」

    awk教程「建议收藏」AWK介绍 0.awk有3个不同版本:awk、nawk和gawk,未作特别说明,一般指gawk。 1.awk语言的最基本功能是在文件或字符串中基于指定规则来分解抽取信息,也可以基于指定的规则来输出数据。完整的awk脚本通常用来格式化文本文件中的信息。 2.三种方式调用awk 1)awk[opion]’awk_script’input_file1[input_file

    2022年7月11日
    11
  • 少儿编程网站有哪些(少儿编程哪家好)

    20个热门少儿编程网站【2019】转载之本文链接:https://blog.csdn.net/shebao3333/article/details/85317936少儿编程是新的文化潮流,它涵盖了儿童学习的方方面面:逻辑思维训练、系统化思考训练、问题解决能力训练、团队协作、创造性思维培养…你可以利用我们整理的这些得到广泛认可的少儿编程网站教孩子学会编程,例如code.org、tynker.c…

    2022年4月18日
    38
  • Java applet详解

    Java applet详解1.为啥使用applet?如果不是因为计算机二级或是某些该死的考试中需要出题,,我想我是不会理会这中东西的,毕竟这货淘汰了,为啥使用?为了考试。注:applet是和html或者是jsp一起使用的,不能单独运行(当然你可以使用appletviewer命令或者是ide去运行),具体的使用将在代码中体现。2.applet生命周期初始化init():在这个方法中可以设置一些初始值…

    2022年7月8日
    20
  • java反射机制简单介绍

    java反射机制简单介绍

    2021年11月14日
    46
  • jsp学习笔记

    jsp学习笔记

    2021年10月3日
    42
  • 团队分工

    团队分工

    2021年11月18日
    58

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号