标签:线程 jdk1.4 技术分享 接下来 cto rda 读取文件 dex mil
Java nio 与 io最基本的差别
Nio是面向缓冲的。能够双向,不管是读写,数据都会被先放到一个缓冲区
Nio 是非堵塞的。当一个线程从通道发出读/写的请求的时候,数据会被先放到缓冲区里。而不须要等待所有读写完毕,在此期间。这个线程能够去做别的事情,通常在空暇时候会运行其它通道上的io操作,一个线程能够管理多个通道
Buffer
前面已经提到,Nio是面向缓冲区的。全部的读写都要先放到缓冲区。
全部的缓冲区类型都继承于抽象类Buffer,最经常使用的是Bytebuffer, java基础类基本上都有相应的buffer类来一一相应。类继承关系图例如以下:
Channel
通道和io的流类似,主要差别为:通道是双向的,可读可写,io流是单向的。仅仅能读或写,并且操作通道不会直接从通道中写入或读取数据。都是由通道将数据放入缓冲区(buffer)中。
最经常使用的通道:
Filechannel 读取/写入 文件数据
Socketchannel TCP协议的socket 读写数据
Datagramchannel UDP协议读写数据
以下是客服端发送读或写的请求过程。
用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(); } }
这里介绍了javaio和nio的差别,以及nio的主要概念。还有简单的nio读写文件数据的样例,对nio就不做深入了。
有兴趣的同学能够看Jakob Jenkov的系列文章。http://tutorials.jenkov.com/java-nio/index.html
接下来会分享nio框架netty的一些学习心得,以及netty在实际项目架构中的使用
标签:线程 jdk1.4 技术分享 接下来 cto rda 读取文件 dex mil
原文地址:http://www.cnblogs.com/brucemengbm/p/6937591.html