Java NIO之Channel(通道)入门

敖胤 2021-01-14 18:08:03
java 通道 channel 入门 NIO


Channel(通道)是专用于IO请求的独立处理器。用于在数据源与目标节点之间建立连接。负责缓冲区中数据的传输。

Java NIO的通道类似流,但又有些不同:

  • 既可以从通道中读取数据,又可以写数据到通道。但流的读写通常是单向的。
  • 通道可以异步地读写。
  • 通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。

Channel可以看做是铁路,Buffer可以看作是列车,而Data数据可以看做是旅客。

1、Channel的实现

以下是Java NIO中最重要的通道的实现:

  • FileChannel:用于从文件中读写数据
  • DatagramChannel:能通过UDP读写网络中的数据
  • SocketChannel:能通过TCP读写网络中的数据(客户端)
  • ServerSocketChannel:可以监听新进来的TCP连接(服务端,像Web服务器那样)对每一个新进来的连接都会创建一个SocketChannel

2、Channel UML图

3、Channel使用示例(FileChannel)

3.1、JDK1.7之前

31.1、RandomAccessFile
FileChannel readChannel = null;
FileChannel writeChannel = null;
try {
RandomAccessFile sourceFile = new RandomAccessFile("demo.txt", "rw");//指定源文件及操作方式
RandomAccessFile dstFile = new RandomAccessFile("demo2.txt", "rw");//指定目标文件及操作方式
//分辨获取
readChannel = sourceFile.getChannel();
writeChannel = dstFile.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (-1 != readChannel.read(byteBuffer)) {
byteBuffer.flip();
writeChannel.write(byteBuffer);
byteBuffer.clear();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
readChannel.close();
writeChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
3.1.2、FileInputStream/FileOutputStream
FileInputStream fips = null;
FileOutputStream fops = null;
FileChannel fipsChannel = null;
FileChannel fopsChannel = null;
try {
fips = new FileInputStream(new File("demo.txt"));
fops = new FileOutputStream(new File("demo2.txt"));
fipsChannel = fips.getChannel();
fopsChannel = fops.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (-1 != fipsChannel.read(byteBuffer)) {
byteBuffer.flip();
fopsChannel.write(byteBuffer);
byteBuffer.clear();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fips.close();
fops.flush();
fops.close();
fipsChannel.close();
fopsChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}

3.2、JDK1.7开始

通过FileChannel的public static FileChannel open(Path path, OpenOption... options) 静态方法

try {
//获取读写通道 StandardOpenOption.CREATE表示——不存在则创建,存在则覆盖
FileChannel inChannel = FileChannel.open(Paths.get("demo.txt"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("demo2.txt"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
//使用内存映射文件方式读写数据(只有ByteBuffer支持)
MappedByteBuffer inBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outBuffer = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());
//读写数据
byte[] dst = new byte[inBuffer.limit()];
inBuffer.get(dst);
outBuffer.put(dst);
} catch (IOException e) {
e.printStackTrace();
}

4、Channel通信

public abstract long transferFrom(ReadableByteChannel src, long position, long count)

public abstract long transferTo(long position, long count, WritableByteChannel target)

try {
FileChannel inChannel = FileChannel.open(Paths.get("demo.txt"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("demo4.txt"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
//inChannel.transferTo(0, inChannel.size(), outChannel);
outChannel.transferFrom(inChannel,0,inChannel.size());
inChannel.close();
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
版权声明
本文为[敖胤]所创,转载请带上原文链接,感谢
https://www.cnblogs.com/wind-ranger/p/14278615.html

  1. Learn about RPC, why RPC was born, and what's the difference between RPC and HTTP?
  2. Learn about RPC, why RPC was born, and what's the difference between RPC and HTTP?
  3. Learn java base conversion supplementary learning
  4. JDBC测试连接数据库
  5. JDBC test connection database
  6. 大厂面试官竟然这么爱问Kafka,一连八个Kafka问题把我问蒙了?
  7. The interviewers of big factories love to ask Kafka so much. I'm blinded by eight Kafka questions in a row?
  8. 安卓开发和java开发有什么区别!2021年BATJ30套大厂Android经典高频面试题,面试必问
  9. Spring Security OAuth2.0認證授權四:分散式系統認證授權
  10. What's the difference between Android development and java development! 2021 batj30 Android classic high frequency interview questions
  11. Spring security oauth2.0 authentication and authorization 4: distributed system authentication and authorization
  12. Java微服务 vs Go微服务,究竟谁更强!?
  13. 大厂面试官竟然这么爱问Kafka,一连八个Kafka问题把我问蒙了?
  14. Who is stronger, Java microservice vs go microservice!?
  15. Java微服务 vs Go微服务,究竟谁更强!?
  16. The interviewers of big factories love to ask Kafka so much. I'm blinded by eight Kafka questions in a row?
  17. Who is stronger, Java microservice vs go microservice!?
  18. springboot异常处理之404
  19. Spring boot exception handling 404
  20. Spring Boot Security 国际化 多语言 i18n 趟过巨坑
  21. springboot异常处理之404
  22. Spring boot security international multilingual I18N
  23. Spring boot exception handling 404
  24. Netty系列化之Google Protobuf编解码
  25. Netty之编解码
  26. Java编解码
  27. Netty解码器
  28. Netty与TCP粘包拆包
  29. Netty开发入门
  30. Java集合遍历时遇到的坑
  31. Spring IOC 源码解析(下)
  32. Spring IoC源码解析(上)
  33. Google protobuf codec of netty serialization
  34. Encoding and decoding of netty
  35. Java codec
  36. Netty decoder
  37. Netty and TCP packet sticking and unpacking
  38. Introduction to netty development
  39. Problems encountered in Java collection traversal
  40. Spring IOC source code analysis (2)
  41. Spring IOC source code analysis (Part one)
  42. 半小时用Spring Boot注解实现Redis分布式锁
  43. Implementing redis distributed lock with spring boot annotation in half an hour
  44. What should we do if we can't get tickets for Spring Festival transportation? You can solve this problem by using these ticket grabbing apps!
  45. 百度智能(文本识别),API传图OC代码与SDK使用
  46. springboot源码解析-管中窥豹系列之aware(六)
  47. Baidu intelligent (text recognition), API map, OC code and SDK
  48. Spring boot source code analysis
  49. springboot源码解析-管中窥豹系列之aware(六)
  50. 百度智能(文本识别),API传图OC代码与SDK使用
  51. Spring boot source code analysis
  52. Baidu intelligent (text recognition), API map, OC code and SDK
  53. Java学习笔记
  54. Java learning notes
  55. Sentry(v20.12.1) K8S 雲原生架構探索, SENTRY FOR JAVASCRIPT 手動捕獲事件基本用法
  56. 我的程式設計師之路:自學Java篇
  57. SpringBoot專案,如何優雅的把介面引數中的空白值替換為null值?
  58. Sentry (v20.12.1) k8s cloud native architecture exploration, sentry for JavaScript manual capture event basic usage
  59. My way of programmer: self study java
  60. Spring boot project, how to gracefully replace the blank value in the interface argument with null value?