博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NIO学习之Channel
阅读量:4323 次
发布时间:2019-06-06

本文共 1162 字,大约阅读时间需要 3 分钟。

一、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

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提供的异步操作文件类

 

转载于:https://www.cnblogs.com/jalja/p/10855009.html

你可能感兴趣的文章
项目管理的小故事
查看>>
Visual Studio不显示智能提示代码,快捷键Alt+→也不出现
查看>>
多文件调用(函数、结构体)
查看>>
C# 获取本地电脑所有的盘符
查看>>
D3.js学习(三)
查看>>
汇编语言实验9
查看>>
window资源管理器下无法打开ftp站点
查看>>
spring特点与好处
查看>>
html 自制属性
查看>>
面向对象术语概念
查看>>
细胞(cell) 矩阵快速幂
查看>>
HDU - 1272 小希的迷宫
查看>>
EntityFramework(1)基础概念与Database First
查看>>
Spring Boot 任务
查看>>
2018APIO 进京赶考
查看>>
Duilib程序添加托盘图标显示
查看>>
在windows上搭建redis集群(redis-cluster)
查看>>
【省选十连测之九】【DP】【组合计数去重】【欧拉函数】基本题
查看>>
文件上传功能 -- jquery.form.js/springmvc
查看>>
阿里云ecs(phpstudy一件包)
查看>>