##Buffer的基本用法
使用Buffer读写数据一般遵循以下四个步骤:

写入数据到Buffer
调用flip()方法
从Buffer中读取数据
调用clear()方法或者compact()方法

当向buffer写入数据时,buffer会记录下写了多少数据。一旦要读取数据,需要通过flip()方法将Buffer从写模式切换到读模式。在读模式下,可以读取之前写入到buffer的所有数据。

一旦读完了所有的数据,就需要清空缓冲区,让它可以再次被写入。有两种方式能清空缓冲区:调用clear()或compact()方法。clear()方法会清空整个缓冲区。compact()方法只会清除已经读过的数据。任何未读的数据都被移到缓冲区的起始处,新写入的数据将放到缓冲区未读数据的后面。

下面两个例子就是两个方法的区别,compact()需要最后再循环一下,来保证数据被传输完,两个方法对比,即使compact()方法更节省一点,就向写写文章,在上次没写完的地方接着写,而clear()则会重新拿一张新的只开始写

下面的例子是网上找的,我自己有一些疑问channelCopy1 中为什么会存在部分读取的情况,每次 dest.write(buffer);不是都会读取完数据完 从 src中写入的数据吗?应该不会有没读取完的数据啊?

 package com.unis.io;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.Channels;import java.nio.channels.ReadableByteChannel;import java.nio.channels.WritableByteChannel;public class channelTest {public static void main(String[] args) throws IOException {ReadableByteChannel source = Channels.newChannel(System.in);WritableByteChannel dest = Channels.newChannel(System.out);channelCopy1(source, dest);// alternatively, call channelCopy2 (source, dest);System.out.println(100);source.close();dest.close();}/*** Channel copy method 1. This method copies data from the src* channel and writes it to the dest channel until EOF on src.* This implementation makes use of compact( ) on the temp buffer * to pack down the data if the buffer wasn't fully drained. This * may result in data copying, but minimizes system calls. It also * requires a cleanup loop to make sure all the data gets sent.*/private static void channelCopy1(ReadableByteChannel src,WritableByteChannel dest)throws IOException {ByteBuffer buffer = ByteBuffer.allocateDirect(3 );while (src.read(buffer) != -1) {// Prepare the buffer to be drainedbuffer.flip();// Write to the channel; may blockdest.write(buffer);// If partial transfer, shift remainder down// If buffer is empty, same as doing clear( )buffer.compact();}// EOF will leave buffer in fill statebuffer.flip();// Make sure that the buffer is fully drainedwhile (buffer.hasRemaining()) {dest.write(buffer);}}/*** Channel copy method 2. This method performs the same copy, but* assures the temp buffer is empty before reading more data. This* never requires data copying but may result in more systems calls.* No post-loop cleanup is needed because the buffer will be empty* when the loop is exited.*/private static void channelCopy2(ReadableByteChannel src,WritableByteChannel dest)throws IOException {ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);while (src.read(buffer) != -1) {// Prepare the buffer to be drainedbuffer.flip();// Make sure that the buffer was fully drainedwhile (buffer.hasRemaining()) {dest.write(buffer);}// Make the buffer empty, ready for fillingbuffer.clear();}}}

java 的 clear 和 compact相关推荐

  1. ByteBuffer中的flip()、clear()、compact()

    NIO读取文件流的简单demo: public static void main(String[] args) {try (FileChannel channel = new FileInputStr ...

  2. java list clear 垃圾回收_list.clear()vs list = new ArrayList Integer(); [重复]

    问题 这个问题在这里已有答案: 清空一个ArrayList或者只是创建一个新的ArrayList并将旧的那个垃圾收集? [重复] 4个答案 Map.clear()vs new Map:哪一个更好? [ ...

  3. Java PriorityQueue clear()方法与示例

    PriorityQueue类clear()方法 (PriorityQueue Class clear() method) clear() method is available in java.uti ...

  4. Java LinkedHashMap clear()方法与示例

    LinkedHashMap类的clear()方法 (LinkedHashMap Class clear() method) clear() method is available in java.ut ...

  5. java list clear 垃圾回收_java垃圾回收机制

    1.什么是垃圾回收? 程序的运行必然需要申请内存资源,无效的对象资源如果不及时处理就会一直占有内存资源,最终将导数内存溢出,所以内存资源的管是非常重要了. 1.1.C/C++语言的垃圾回收 在C/C+ ...

  6. Java 缩小字符串( Compact String)和 压缩字符串(Compressed String)

    正如我们在上面文章提到的内容,在英文语境中上面 2 个方法还是有区别的,在中文环境下主要表达就是字符串压缩. JDK 6 使用的压缩字符串方法,主要原因是我们修改了 String 的存储结构,char ...

  7. java list clear 垃圾回收_Java垃圾回收

    1.标记-清除算法 这种收集器首先遍历对象图并标记可到达的对象,然后扫描堆栈以寻找未标记对象并释放它们的内存.这种收集器一般使用单线程工作并停止其他操作. 复制算法 这种收集器将堆栈分为两个域,常称为 ...

  8. java nio rewind_NIO-java.nio.ByteBuffer中flip、rewind、clear方法的区别

    原文链接     作者:Jakob Jenkov     译者:airu     校对:丁一 Java NIO中的Buffer用于和NIO通道进行交互.如你所知,数据是从通道读入缓冲区,从缓冲区写入到 ...

  9. Netty:Java 领域网络编程的王者

    一.简介 1. 课程背景 分布式系统的根基在于网络编程,而 Netty 是 Java 领域网络编程的王者. 2. 课程内容 第一部分 NIO 编程,三大组件 第二部分 Netty 入门学习,Event ...

最新文章

  1. ISME:中大李文均组在放线菌生命暗物质的生态功能与进化上取得进展
  2. 大利好!学历低的算法工程师要起飞了,这波惊喜来的太突然!
  3. error: xxxx.o: Relocations in generic ELF (EM: 3)解决办法
  4. C#调用C++dll
  5. android avd 使用方法,Android中Android Virtual Device(AVD)使用教程
  6. 光端机和收发器的区别有哪些?
  7. 学习笔记(05):MySQL数据库运维与管理-03-二进制日志配置管理演示
  8. linux中用shell获取时间,日期
  9. 用usecase获取需求的方法是否有缺陷,还有什么地方需要改进
  10. 蓝桥杯2015年第六届C/C++省赛C组第二题-立方尾不变
  11. 在 Mac 上的 Pages 文稿中如何添加和替换文本?
  12. dlna和miracast可以共存吗_关于无线显示技术,AirPlay,DLNA,Miracast,WiDi 等有何异同?...
  13. 【分享】班组5S管理实践办法
  14. 第三章 一元函数积分概念、计算及应用
  15. 匿名四轴上位机使用方法
  16. Unity学习:瓦片地图
  17. 【算法设计与分析】图搜索算法的应用
  18. Gartner:新兴技术成熟度曲线2018(中文—历年)
  19. 【真人手势动画制作软件】万彩手影大师教程 | 如何让2个对象同时播放
  20. 特别策划:非计算机专业如何转行做程序员?

热门文章

  1. 8 种实现垂直和水平居中元素的方法汇总
  2. 【单片记笔记】基于STM32F103的NEC红外发送接收使用同一个定时器的一体设计
  3. bat echo命令
  4. 【kubernetes】coredns报错
  5. Vue CLI 脚手架
  6. 自顶向下计算机网络学习 应用层
  7. Mac系统如何进入mysql
  8. error: void value not ignored as it ought to be
  9. MySQL-5.6版本GTID的主从复制
  10. C语言不完全类型是什么?有什么用途?