首页 技术 正文
技术 2022年11月23日
0 收藏 661 点赞 2,226 浏览 1037 个字

一、Channel基础

通道是一个对象,通过它可以读取和写入数据,Channel就是通向什么的道路,为数据的流向提供渠道;

在传统IO中,我们要读取一个文件中的内容使用Inputstream,该stream就是通道,不过在IO中这个通道是单向的,而NIO中Channel是双向的,既可用来进行读操作,又可用来进行写操作;无论读写都作用于Buffer。

1、将数据通过channdel输出到文件

private static void writer( )throws IOException{
String str="I Love China";
byte [] message=str.getBytes("UTF-8");
FileOutputStream fout = new FileOutputStream( filePath );
FileChannel fc = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
for (int i=0; i<message.length; ++i) {
buffer.put( message[i] );
}
buffer.flip();
fc.write( buffer );
fout.close();
}

2、通过channel将数据读入内存

 private static void read( )throws IOException{
FileInputStream inputStream=new FileInputStream(filePath);
FileChannel channel=inputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
channel.read(buffer);
String msg=new String(buffer.array(),"UTF-8");
System.out.println(msg);
inputStream.close();
}

二、channel分类

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

AsynchronousFileChannel:JDK1.7提供的异步操作文件类

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,944
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,469
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,283
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,099
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,729
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,766