java+nio全称_Java nio 概述

Channel

通道和io的流类似,主要差别为:通道是双向的,可读可写,io流是单向的。仅仅能读或写,并且操作通道不会直接从通道中写入或读取数据。都是由通道将数据放入缓冲区(buffer)中。

最经常使用的通道:

Filechannel 读取/写入 文件数据

Socketchannel TCP协议的socket 读写数据

Datagramchannel UDP协议读写数据

以下是客服端发送读或写的请求过程。

SouthEast

用Filechannel往文件里读取和写入数据的简单样例

读取文件内容:

public static void main(String[] args) {

FileInputStream fin = null;

try {

fin = new FileInputStream("c:\\nio.txt");

} catch (FileNotFoundException e) {

e.printStackTrace();

}

// 获取通道

FileChannel fc = fin.getChannel();

// 创建缓冲区

ByteBuffer buffer = ByteBuffer.allocate(1024);

// 读取数据到缓冲区

try {

fc.read(buffer);

} catch (IOException e) {

e.printStackTrace();

}

buffer.flip();

while (buffer.remaining() > 0) {

byte b = buffer.get();

System.out.print(((char) b));

}

try {

fin.close();

} catch (IOException e) {

e.printStackTrace();

}

}

写入文件内容:

public static void main(String[] args) {

File file = new File("c:\\nio.txt");

FileOutputStream outputStream = null;

try {

outputStream = new FileOutputStream(file);

} catch (FileNotFoundException e1) {

e1.printStackTrace();

}

FileChannel channel = outputStream.getChannel();

ByteBuffer bufferWrite = ByteBuffer.allocate(1024);

String string = "hello nio...";

bufferWrite.put(string.getBytes());

//这里必须调用flip(),先读取数据到Buffer。再从Buffer中读取数据。

bufferWrite.flip();

try {

channel.write(bufferWrite);

channel.close();

outputStream.close();

} catch (IOException e1) {

e1.printStackTrace();

}

}

Select

Select 能检測到注冊的全部通道上是否有读写请求,当有请求的时候才会进行读写,一个线程管理了多个通道。避免了多线程切换导致的开销。也不用去维护多个线程,操作原理例如以下图

808f9da363f02ef12695da654707ab23.png

这里介绍了javaio和nio的差别,以及nio的主要概念。还有简单的nio读写文件数据的样例,对nio就不做深入了。

有兴趣的同学能够看Jakob Jenkov的系列文章。http://tutorials.jenkov.com/java-nio/index.html

接下来会分享nio框架netty的一些学习心得,以及netty在实际项目架构中的使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值