1. package com.slp.nio;
  2.  
  3. import org.junit.Test;
  4.  
  5. import java.io.*;
  6. import java.nio.ByteBuffer;
  7. import java.nio.CharBuffer;
  8. import java.nio.MappedByteBuffer;
  9. import java.nio.channels.FileChannel;
  10. import java.nio.charset.CharacterCodingException;
  11. import java.nio.charset.Charset;
  12. import java.nio.charset.CharsetDecoder;
  13. import java.nio.charset.CharsetEncoder;
  14. import java.nio.file.Paths;
  15. import java.nio.file.StandardOpenOption;
  16. import java.util.Map;
  17. import java.util.Set;
  18.  
  19. /**
  20. * Created by sanglp on 2017/3/1.
  21. * 一、通道:用于源节点与目标节点的连接,在Java NIO中负责缓冲区中数据的传输。通道本身是不存储任何数据的,因此需要配合缓冲区进行传输数据
  22. * 二、通道的一些主要实现类
  23. * java.nio.Channel接口
  24. * |--FileChannel
  25. * |--SocketChannel
  26. * |--ServerSocketChannel
  27. * |--DatagramChannel
  28. * 三、获取通道
  29. * 1.java针对支持通道的类提供了getChannel()方法
  30. * 本地IO:
  31. * FileInputStream/FileOutputStream/RandomAccessFile
  32. * 网络IO:
  33. * Socket
  34. * ServerSocket
  35. * DategramSocket
  36. * 2.在jdk1.7中的NIO2针对各个通道提供了一个静态方法open()
  37. * 3。jdk1.7中的NIO2的Files工具类的newByteChannel()
  38. * 四、通道之间的数据传输
  39. * transferFrom()
  40. * transferTo()
  41. * 五、分散和聚集
  42. * 分散度区:将通道中的数据分散到多个缓冲区中
  43. * 聚集写入:将多个缓冲区中的数据聚集到通道中
  44. *
  45. * 六、字符集:Charset
  46. * 编码:字符串->字节数组
  47. * 解码:字节数组->字符串
  48. */
  49. public class TestChannel {
  50. @Test
  51. public void test6() throws CharacterCodingException {
  52. Charset cs1 = Charset.forName("GBK");
  53. //获取编码器和解码器
  54. CharsetEncoder ce = cs1.newEncoder();
  55. //获取解码器
  56. CharsetDecoder cd = cs1.newDecoder();
  57.  
  58. CharBuffer charBuffer = CharBuffer.allocate(1024);
  59. charBuffer.put("桑丽平加油!!");
  60. charBuffer.flip();
  61.  
  62. //编码
  63. ByteBuffer byteBuffer = ce.encode(charBuffer);
  64. for (int i=0;i<12;i++){
  65. System.out.println(byteBuffer.get(i));
  66. }
  67.  
  68. //解码
  69. byteBuffer.flip();
  70. CharBuffer charBuffer1 = cd.decode(byteBuffer);
  71. System.out.println(charBuffer1.toString());
  72.  
  73. System.out.println("------------------------");
  74.  
  75. Charset cs2 = Charset.forName("UTF-8");
  76. byteBuffer.flip();
  77. CharBuffer cBuf3 =cs2.decode(byteBuffer);
  78. System.out.println(cBuf3.toString());
  79. }
  80.  
  81. @Test
  82. public void test5(){
  83. Map<String,Charset> map=Charset.availableCharsets();
  84. Set<Map.Entry<String,Charset>> set = map.entrySet();
  85. for (Map.Entry<String,Charset> entry :set ){
  86. System.out.println(entry.getKey()+"="+entry.getValue());
  87. }
  88. }
  89. @Test
  90. public void test4() throws IOException {
  91. RandomAccessFile randomAccessFile = new RandomAccessFile("1.txt","rw");
  92. //获取通道
  93. FileChannel channel = randomAccessFile.getChannel();
  94. //分配指定大小的缓冲区
  95. ByteBuffer buffer1 = ByteBuffer.allocate(100);
  96. ByteBuffer buffer2 = ByteBuffer.allocate(1024);
  97. //分散读取
  98. ByteBuffer [] bufs = {buffer1,buffer2};
  99. channel.read(bufs);
  100. for (ByteBuffer byteBuffer:bufs){
  101. byteBuffer.flip();
  102. }
  103.  
  104. System.out.println(new String(bufs[0].array(),0,bufs[0].limit()));
  105. System.out.println("---------------");
  106. System.out.println(new String(bufs[1].array(),0,bufs[1].limit()));
  107.  
  108. //聚集写入
  109. RandomAccessFile randomAccessFile1 = new RandomAccessFile("2.txt","rw");
  110. FileChannel channel1 = randomAccessFile1.getChannel();
  111. channel1.write(bufs);
  112.  
  113. }
  114.  
  115. //通道之间的数据传输(直接缓冲区)
  116. @Test
  117. public void test3() throws IOException {
  118. FileChannel fileChannel = FileChannel.open(Paths.get("pipe.bmp"), StandardOpenOption.READ);
  119. FileChannel outChannel =FileChannel.open(Paths.get("4.bmp"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);
  120.  
  121. fileChannel.transferTo(0,fileChannel.size(),outChannel);
  122. //outChannel.transferFrom(fileChannel,0,fileChannel.size());或者
  123. fileChannel.close();
  124. outChannel.close();
  125. }
  126.  
  127. //2、利用直接缓冲区完成文件的复制(内存映射文件)
  128. @Test
  129. public void test2() throws IOException {
  130. FileChannel fileChannel = FileChannel.open(Paths.get("pipe.bmp"), StandardOpenOption.READ);
  131. FileChannel outChannel =FileChannel.open(Paths.get("3.bmp"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);
  132. //内存映射文件
  133. MappedByteBuffer imMappedBuf = fileChannel.map(FileChannel.MapMode.READ_ONLY,0,fileChannel.size());
  134. MappedByteBuffer outMappedBuf = outChannel.map(FileChannel.MapMode.READ_WRITE,0,fileChannel.size());
  135. //直接对缓冲区进行数据的读写操作
  136. byte [] dst = new byte[imMappedBuf.limit()];
  137. imMappedBuf.get(dst);
  138. outMappedBuf.put(dst);
  139.  
  140. fileChannel.close();
  141. outChannel.close();
  142.  
  143. }
  144.  
  145. //1、利用通道完成文件的复制(费直接缓冲区)
  146. @org.junit.Test
  147. public void test1(){
  148. FileInputStream fis =null;
  149. FileOutputStream fos =null;
  150. FileChannel inChanne=null;
  151. FileChannel outChannel=null;
  152. try{
  153. fis = new FileInputStream("pipe.bmp");
  154. fos = new FileOutputStream("2.jpg");
  155. //获取通道
  156. inChanne =fis.getChannel();
  157. outChannel = fos.getChannel();
  158. //分配指定大小的缓冲区
  159. ByteBuffer buffer = ByteBuffer.allocate(1024);
  160. //将通道中的数据存入缓冲区中
  161. while (inChanne.read(buffer)!=-1) {
  162. buffer.flip();//切换为读取数据的模式
  163. //将缓冲区中的数据写入通道
  164. outChannel.write(buffer);
  165. buffer.clear();//清空缓冲区
  166. }
  167. }catch (IOException e){
  168. e.printStackTrace();
  169. }finally {
  170. if(outChannel!=null){
  171. try {
  172. outChannel.close();
  173. } catch (IOException e) {
  174. e.printStackTrace();
  175. }
  176. }
  177. if(inChanne!=null){
  178. try {
  179. inChanne.close();
  180. } catch (IOException e) {
  181. e.printStackTrace();
  182. }
  183. }
  184.  
  185. if(fis!=null){
  186. try {
  187. fis.close();
  188. } catch (IOException e) {
  189. e.printStackTrace();
  190. }
  191. }
  192. if(fos!=null){
  193. try {
  194. fos.close();
  195. } catch (IOException e) {
  196. e.printStackTrace();
  197. }
  198. }
  199. }
  200.  
  201. }
  202. }

【Java nio】Channel的更多相关文章

  1. 【Java nio】 NonBlocking NIO

    package com.slp.nio; import org.junit.Test; import java.io.IOException; import java.net.InetSocketAd ...

  2. 【Java nio】 Blocking nio

    package com.slp.nio; import org.junit.Test; import java.io.File; import java.io.IOException; import ...

  3. 【Java nio】java nio笔记

    缓冲区操作:缓冲区,以及缓冲区如何工作,是所有I/O的基础.所谓“输入/输出”讲的无非就是把数据移出货移进缓冲区.进程执行I/O操作,归纳起来也就是向操作系统发出请求,让它要么把缓冲区里的数据排干,要 ...

  4. 【Java NIO】一文了解NIO

    Java NIO 1 背景介绍 在上一篇文章中我们介绍了Java基本IO,也就是阻塞式IO(BIO),在JDK1.4版本后推出了新的IO系统(NIO),也可以理解为非阻塞IO(Non-Blocking ...

  5. 【JAVA NIO】java NIO

    本文是博主深入学习Netty前的一些铺垫,之前只是使用Netty,用的很粗暴,导包,上网找个DEMO就直接用,对Netty中的组件了解并不深入. 于是再此总结下基础,并对一些核心组件作如下记录: 1. ...

  6. 【Java nio】Blocking nio2

    package com.slp.nio; import org.junit.Test; import java.io.File; import java.io.IOException; import ...

  7. 【Java nio】buffer

    package com.slp.nio; import org.junit.Test; import java.nio.ByteBuffer; /** * Created by sanglp on 2 ...

  8. 【java NIO】服务器端读写图片的一次排错经历

    上传文件方面: 一.前端 使用的是jQuery框架来上传图片,参考的是harttle大神博客:http://harttle.com/2016/07/04/jquery-file-upload.html ...

  9. 【Java面试】基础知识篇

    [Java面试]基础知识篇 Java基础知识总结,主要包括数据类型,string类,集合,线程,时间,正则,流,jdk5--8各个版本的新特性,等等.不足的地方,欢迎大家补充.源码分享见个人公告.Ja ...

随机推荐

  1. JavaScrip——DOM操作(查找HTML元素/修改元素)

    innerHTML 1.查找元素——document.getElementById("intro") 2.输出查找的结果: (1)var a=document.getElement ...

  2. C/C++捕获段错误,打印出错的具体位置(精确到哪一行)_转

    转自:C/C++捕获段错误,打印出错的具体位置(精确到哪一行) 修订:2013-02-16 其实还可以使用 glibc 的 backtrace_symbols 函数,把栈帧各返回地址里面的数字地址翻译 ...

  3. Spring - BeanFactory 新旧工厂差异

    在将要被加入到spring容器中的service中,添加static静态代码块(加载类时被调用),用于判断spring中新旧bean工厂的加载性质. package com.witwicky.serv ...

  4. java-servlet 新增特性 注释

    package com.gordon.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.ser ...

  5. e647. 处理鼠标移动事件

    component.addMouseMotionListener(new MyMouseMotionListener()); public class MyMouseMotionListener ex ...

  6. FFMPEG的解码后的数据格式

    这两天在阅读电视转发服务器中的流媒体底层库的源码时,在看到显示部分的时候,遇到了一些疑问: 就是在用d3d做显示时候,我们显示的数据格式,指定为yv12,对于YV12的数据格式在内存中的分布,可以参考 ...

  7. linux -- 进程的查看、进程id的获取、进程的杀死

    进程查看 ps ax : 显示当前系统进程的列表 ps aux : 显示当前系统进程详细列表以及进程用户 ps ax|less : 如果输出过长,可能添加管道命令 less查看具体进程, 如:ps a ...

  8. 【Java面试题】39 Set里的元素是不能重复的,那么用什么方法来区分重复与否呢? 是用==还是equals()? 它们有何区别?

    1.什么是Set?(what) Set是Collection容器的一个子接口,它不允许出现重复元素,当然也只允许有一个null对象. 2.如何来区分重复与否呢?(how) “ 用 iterator() ...

  9. u3d调用c++ dll的DllNotFoundExceion 问题

    原文地址:http://blog.csdn.net/boren31/article/details/8778504 问题年年有,今年特别多. 开发环境: Windows  XP sp3 Visual  ...

  10. 轻量级iOS安全框架:SSKeyChain

    原文地址: http://blog.csdn.net/kmyhy/article/details/7261065 SSKeyChains对苹果安全框架API进行了简单封装,支持对存储在钥匙串中密码.账 ...