java.io和util的区别_Java NIO与IO的区别和比较
Java NIO與IO的區(qū)別和比較
導(dǎo)讀
J2SE1.4以上版本中發(fā)布了全新的I/O類庫。本文將通過一些實例來簡單介紹NIO庫提供的一些新特性:非阻塞I/O,字符轉(zhuǎn)換,緩沖以及通道。
一. 介紹NIO
NIO包(java.nio.*)引入了四個關(guān)鍵的抽象數(shù)據(jù)類型,它們共同解決傳統(tǒng)的I/O類中的一些問題。Buffer:它是包含數(shù)據(jù)且用于讀寫的線形表結(jié)構(gòu)。其中還提供了一個特殊類用于內(nèi)存映射文件的I/O操作。
Charset:它提供Unicode字符串影射到字節(jié)序列以及逆影射的操作。
Channels:包含socket,file和pipe三種管道,它實際上是雙向交流的通道。
Selector:它將多元異步I/O操作集中到一個或多個線程中(它可以被看成是Unix中select()函數(shù)或Win32中WaitForSingleEvent()函數(shù)的面向?qū)ο蟀姹?。
二. 回顧傳統(tǒng)
在介紹NIO之前,有必要了解傳統(tǒng)的I/O操作的方式。以網(wǎng)絡(luò)應(yīng)用為例,傳統(tǒng)方式需要監(jiān)聽一個ServerSocket,接受請求的連接為其提供服務(wù)(服務(wù)通常包括了處理請求并發(fā)送響應(yīng))圖一是服務(wù)器的生命周期圖,其中標(biāo)有粗黑線條的部分表明會發(fā)生I/O阻塞。
圖一
//可以分析創(chuàng)建服務(wù)器的每個具體步驟。首先創(chuàng)建ServerSocket
ServerSocket server=new ServerSocket(10000);//然后接受新的連接請求
Socket newConnection=server.accept();//對于accept方法的調(diào)用將造成阻塞,直到ServerSocket接受到一個連接請求為止。一旦連接請求被接受,服務(wù)器可以讀客戶socket中的請求。
InputStream in =newConnection.getInputStream();
InputStreamReader reader= newInputStreamReader(in);
BufferedReader buffer= newBufferedReader(reader);
Request request= newRequest();while(!request.isComplete()) {
String line=buffer.readLine();
request.addLine(line);
這樣的操作有兩個問題,首先BufferedReader類的readLine()方法在其緩沖區(qū)未滿時會造成線程阻塞,只有一定數(shù)據(jù)填滿了緩沖區(qū)或者客戶關(guān)閉了套接字,方法才會返回。其次,它回產(chǎn)生大量的垃圾,BufferedReader創(chuàng)建了緩沖區(qū)來從客戶套接字讀入數(shù)據(jù),但是同樣創(chuàng)建了一些字符串存儲這些數(shù)據(jù)。雖然BufferedReader內(nèi)部提供了StringBuffer處理這一問題,但是所有的String很快變成了垃圾需要回收。
同樣的問題在發(fā)送響應(yīng)代碼中也存在
Response response =request.generateResponse();
OutputStream out=newConnection.getOutputStream();
InputStream in=response.getInputStream();intch;while(-1 != (ch =in.read())) {
out.write(ch);
}
newConnection.close();
類似的,讀寫操作被阻塞而且向流中一次寫入一個字符會造成效率低下,所以應(yīng)該使用緩沖區(qū),但是一旦使用緩沖,流又會產(chǎn)生更多的垃圾。
傳統(tǒng)的解決方法
通常在Java中處理阻塞I/O要用到線程(大量的線程)。一般是實現(xiàn)一個線程池用來處理請求,如圖二
圖二
線程使得服務(wù)器可以處理多個連接,但是它們也同樣引發(fā)了許多問題。每個線程擁有自己的棧空間并且占用一些CPU時間,耗費很大,而且很多時間是浪費在阻塞的I/O操作上,沒有有效的利用CPU。
三. 新I/O
1.?Buffer
傳統(tǒng)的I/O不斷的浪費對象資源(通常是String)。新I/O通過使用Buffer讀寫數(shù)據(jù)避免了資源浪費。Buffer對象是線性的,有序的數(shù)據(jù)集合,它根據(jù)其類別只包含唯一的數(shù)據(jù)類型。
java.nio.Buffer //類描述
java.nio.ByteBuffer //包含字節(jié)類型。 可以從ReadableByteChannel中讀在 WritableByteChannel中寫
java.nio.MappedByteBuffer //包含字節(jié)類型,直接在內(nèi)存某一區(qū)域映射
java.nio.CharBuffer //包含字符類型,不能寫入通道
java.nio.DoubleBuffer //包含double類型,不能寫入通道
java.nio.FloatBuffer //包含float類型
java.nio.IntBuffer //包含int類型
java.nio.LongBuffer //包含long類型
java.nio.ShortBuffer //包含short類型
可以通過調(diào)用allocate(int capacity)方法或者allocateDirect(int capacity)方法分配一個Buffer。特別的,你可以創(chuàng)建MappedBytesBuffer通過調(diào)用FileChannel.map(int mode,long position,int size)。直接(direct)buffer在內(nèi)存中分配一段連續(xù)的塊并使用本地訪問方法讀寫數(shù)據(jù)。非直接(nondirect)buffer通過使用Java中的數(shù)組訪問代碼讀寫數(shù)據(jù)。有時候必須使用非直接緩沖例如使用任何的wrap方法(如ByteBuffer.wrap(byte[]))在Java數(shù)組基礎(chǔ)上創(chuàng)建buffer。
2. 字符編碼
向ByteBuffer中存放數(shù)據(jù)涉及到兩個問題:字節(jié)的順序和字符轉(zhuǎn)換。ByteBuffer內(nèi)部通過ByteOrder類處理了字節(jié)順序問題,但是并沒有處理字符轉(zhuǎn)換。事實上,ByteBuffer沒有提供方法讀寫String。
Java.nio.charset.Charset處理了字符轉(zhuǎn)換問題。它通過構(gòu)造CharsetEncoder和CharsetDecoder將字符序列轉(zhuǎn)換成字節(jié)和逆轉(zhuǎn)換。
3. 通道(Channel)
你可能注意到現(xiàn)有的java.io類中沒有一個能夠讀寫B(tài)uffer類型,所以NIO中提供了Channel類來讀寫B(tài)uffer。通道可以認(rèn)為是一種連接,可以是到特定設(shè)備,程序或者是網(wǎng)絡(luò)的連接。通道的類等級結(jié)構(gòu)圖如下
圖三
圖中ReadableByteChannel和WritableByteChannel分別用于讀寫。
GatheringByteChannel可以從使用一次將多個Buffer中的數(shù)據(jù)寫入通道,相反的,ScatteringByteChannel則可以一次將數(shù)據(jù)從通道讀入多個Buffer中。你還可以設(shè)置通道使其為阻塞或非阻塞I/O操作服務(wù)。
為了使通道能夠同傳統(tǒng)I/O類相容,Channel類提供了靜態(tài)方法創(chuàng)建Stream或Reader
4.?Selector
在過去的阻塞I/O中,我們一般知道什么時候可以向stream中讀或?qū)?#xff0c;因為方法調(diào)用直到stream準(zhǔn)備好時返回。但是使用非阻塞通道,我們需要一些方法來知道什么時候通道準(zhǔn)備好了。在NIO包中,設(shè)計Selector就是為了這個目的。SelectableChannel可以注冊特定的事件,而不是在事件發(fā)生時通知應(yīng)用,通道跟蹤事件。然后,當(dāng)應(yīng)用調(diào)用Selector上的任意一個selection方法時,它查看注冊了的通道看是否有任何感興趣的事件發(fā)生。圖四是selector和兩個已注冊的通道的例子
并不是所有的通道都支持所有的操作。SelectionKey類定義了所有可能的操作位,將要用兩次。首先,當(dāng)應(yīng)用調(diào)用SelectableChannel.register(Selector sel,int op)方法注冊通道時,它將所需操作作為第二個參數(shù)傳遞到方法中。然后,一旦SelectionKey被選中了,SelectionKey的readyOps()方法返回所有通道支持操作的數(shù)位的和。SelectableChannel的validOps方法返回每個通道允許的操作。注冊通道不支持的操作將引發(fā)IllegalArgumentException異常。下表列出了SelectableChannel子類所支持的操作。
IllegalArgumentException異常。下表列出了SelectableChannel子類所支持的操作。
ServerSocketChannel OP_ACCEPT
SocketChannel OP_CONNECT, OP_READ, OP_WRITE
DatagramChannel OP_READ, OP_WRITE
Pipe.SourceChannel OP_READ
Pipe.SinkChannel OP_WRITE
四. 舉例說明
1. 簡單網(wǎng)頁內(nèi)容下載
這個例子非常簡單,類SocketChannelReader使用SocketChannel來下載特定網(wǎng)頁的HTML內(nèi)容。
importjava.nio.ByteBuffer;importjava.nio.channels.SocketChannel;importjava.nio.charset.Charset;importjava.net.InetSocketAddress;importjava.io.IOException;public classSocketChannelReader {private Charset charset = Charset.forName("UTF-8");//創(chuàng)建UTF-8字符集
privateSocketChannel channel;public voidgetHTMLContent() {try{
connect();
sendRequest();
readResponse();
}catch(IOException e) {
System.err.println(e.toString());
}finally{if (channel != null) {try{
channel.close();
}catch(IOException e) {
}
}
}
}private void connect() throws IOException {//連接到CSDN
InetSocketAddress socketAddress = newInetSocketAddress("www.csdn.net", 80);
channel=SocketChannel.open(socketAddress);//使用工廠方法open創(chuàng)建一個channel并將它連接到指定地址上//相當(dāng)與SocketChannel.open().connect(socketAddress);調(diào)用
}private void sendRequest() throwsIOException {
channel.write(charset.encode("GET " + "/document" + "\r\n\r\n"));//發(fā)送GET請求到CSDN的文檔中心//使用channel.write方法,它需要CharByte類型的參數(shù),使用//Charset.encode(String)方法轉(zhuǎn)換字符串。
}private void readResponse() throws IOException {//讀取應(yīng)答
ByteBuffer buffer = ByteBuffer.allocate(1024);//創(chuàng)建1024字節(jié)的緩沖
while (channel.read(buffer) != -1) {
buffer.flip();//flip方法在讀緩沖區(qū)字節(jié)操作之前調(diào)用。
System.out.println(charset.decode(buffer));//使用Charset.decode方法將字節(jié)轉(zhuǎn)換為字符串
buffer.clear();//清空緩沖
}
}public static voidmain(String[] args) {try{newSocketChannelReader().getHTMLContent();
}catch(Exception e) {
e.printStackTrace();
}
}
}
2. 簡單的加法服務(wù)器和客戶機(jī)
服務(wù)器代碼
packagemjorcen.nio.test;importjava.nio.ByteBuffer;importjava.nio.IntBuffer;importjava.nio.channels.ServerSocketChannel;importjava.nio.channels.SocketChannel;importjava.net.InetSocketAddress;importjava.io.IOException;/*** SumServer.java
*
*
* Created: Thu Nov 06 11:41:52 2003
*
*@authorstarchu1981
*@version1.0*/
public classSumServer {private ByteBuffer _buffer = ByteBuffer.allocate(8);private IntBuffer _intBuffer =_buffer.asIntBuffer();private SocketChannel _clientChannel = null;private ServerSocketChannel _serverChannel = null;public voidstart() {try{
openChannel();
waitForConnection();
}catch(IOException e) {
System.err.println(e.toString());
}
}private void openChannel() throwsIOException {
_serverChannel=ServerSocketChannel.open();
_serverChannel.socket().bind(new InetSocketAddress(10000));
System.out.println("服務(wù)器通道已經(jīng)打開");
}private void waitForConnection() throwsIOException {while (true) {
_clientChannel=_serverChannel.accept();if (_clientChannel != null) {
System.out.println("新的連接加入");
processRequest();
_clientChannel.close();
}
}
}private void processRequest() throwsIOException {
_buffer.clear();
_clientChannel.read(_buffer);int result = _intBuffer.get(0) + _intBuffer.get(1);
_buffer.flip();
_buffer.clear();
_intBuffer.put(0, result);
_clientChannel.write(_buffer);
}public static voidmain(String[] args) {newSumServer().start();
}
}//SumServer
客戶代碼
packagemjorcen.nio.test;importjava.nio.ByteBuffer;importjava.nio.IntBuffer;importjava.nio.channels.SocketChannel;importjava.net.InetSocketAddress;importjava.io.IOException;/*** SumClient.java
*
*
* Created: Thu Nov 06 11:26:06 2003
*
*@authorstarchu1981
*@version1.0*/
public classSumClient {private ByteBuffer _buffer = ByteBuffer.allocate(8);privateIntBuffer _intBuffer;privateSocketChannel _channel;publicSumClient() {
_intBuffer=_buffer.asIntBuffer();
}//SumClient constructor
public int getSum(int first, intsecond) {int result = 0;try{
_channel=connect();
sendSumRequest(first, second);
result=receiveResponse();
}catch(IOException e) {
System.err.println(e.toString());
}finally{if (_channel != null) {try{
_channel.close();
}catch(IOException e) {
}
}
}returnresult;
}private SocketChannel connect() throwsIOException {
InetSocketAddress socketAddress= new InetSocketAddress("localhost",10000);returnSocketChannel.open(socketAddress);
}private void sendSumRequest(int first, int second) throwsIOException {
_buffer.clear();
_intBuffer.put(0, first);
_intBuffer.put(1, second);
_channel.write(_buffer);
System.out.println("發(fā)送加法請求 " + first + "+" +second);
}private int receiveResponse() throwsIOException {
_buffer.clear();
_channel.read(_buffer);return _intBuffer.get(0);
}public static voidmain(String[] args) {
SumClient sumClient= newSumClient();
System.out.println("加法結(jié)果為 :" + sumClient.getSum(100, 324));
}
}//SumClient
3. 非阻塞的加法服務(wù)器
首先在openChannel方法中加入語句
_serverChannel.configureBlocking(false);//設(shè)置成為非阻塞模式
重寫WaitForConnection方法的代碼如下,使用非阻塞方式 (這里我稍微改了下,不知道對不對, 原來博主的跑不了,)
private void waitForConnection() throwsIOException {
Selector acceptSelector=SelectorProvider.provider().openSelector();/** 在服務(wù)器套接字上注冊selector并設(shè)置為接受accept方法的通知。
* 這就告訴Selector,套接字想要在accept操作發(fā)生時被放在ready表 上,因此,允許多元非阻塞I/O發(fā)生。*/SelectionKey acceptKey=_serverChannel.register(acceptSelector,
SelectionKey.OP_ACCEPT);int keysAdded = 0;/*select方法在任何上面注冊了的操作發(fā)生時返回*/
while ((keysAdded = acceptSelector.select()) > 0) {//某客戶已經(jīng)準(zhǔn)備好可以進(jìn)行I/O操作了,獲取其ready鍵集合
Set readyKeys =acceptSelector.selectedKeys();
Iterator i=readyKeys.iterator();//遍歷ready鍵集合,并處理加法請求
while(i.hasNext()) {
SelectionKey sk=(SelectionKey) i.next();
i.remove();
ServerSocketChannel nextReady=(ServerSocketChannel) sk
.channel();//接受加法請求并處理它
_clientChannel =nextReady.accept().socket().getChannel();
processRequest();
_clientChannel.close();
}
}
}
服務(wù)端整體改完之后代碼:
packagemjorcen.nio.test;importjava.io.IOException;importjava.net.InetSocketAddress;importjava.net.Socket;importjava.nio.ByteBuffer;importjava.nio.IntBuffer;importjava.nio.channels.SelectableChannel;importjava.nio.channels.SelectionKey;importjava.nio.channels.Selector;importjava.nio.channels.ServerSocketChannel;importjava.nio.channels.SocketChannel;importjava.nio.channels.spi.SelectorProvider;importjava.util.Iterator;importjava.util.Set;/*** SumServer.java
*
*
* Created: Thu Nov 06 11:41:52 2003
*
*@authorstarchu1981
*@version1.0*/
public classSumServer {private ByteBuffer _buffer = ByteBuffer.allocate(8);private IntBuffer _intBuffer =_buffer.asIntBuffer();private SocketChannel _clientChannel = null;private ServerSocketChannel _serverChannel = null;public voidstart() {try{
openChannel();
waitForConnection();
}catch(IOException e) {
System.err.println(e.toString());
}
}private void openChannel() throwsIOException {
_serverChannel=ServerSocketChannel.open();
_serverChannel.socket().bind(new InetSocketAddress(10000));
_serverChannel.configureBlocking(false);//設(shè)置成為非阻塞模式
System.out.println("服務(wù)器通道已經(jīng)打開");
}private void waitForConnection() throwsIOException {
Selector acceptSelector=SelectorProvider.provider().openSelector();/** 在服務(wù)器套接字上注冊selector并設(shè)置為接受accept方法的通知。
* 這就告訴Selector,套接字想要在accept操作發(fā)生時被放在ready表 上,因此,允許多元非阻塞I/O發(fā)生。*/SelectionKey acceptKey=_serverChannel.register(acceptSelector,
SelectionKey.OP_ACCEPT);int keysAdded = 0;/*select方法在任何上面注冊了的操作發(fā)生時返回*/
while ((keysAdded = acceptSelector.select()) > 0) {//某客戶已經(jīng)準(zhǔn)備好可以進(jìn)行I/O操作了,獲取其ready鍵集合
Set readyKeys =acceptSelector.selectedKeys();
Iterator i=readyKeys.iterator();//遍歷ready鍵集合,并處理加法請求
while(i.hasNext()) {
SelectionKey sk=(SelectionKey) i.next();
i.remove();
ServerSocketChannel nextReady=(ServerSocketChannel) sk
.channel();//接受加法請求并處理它
_clientChannel =nextReady.accept().socket().getChannel();
processRequest();
_clientChannel.close();
}
}
}private void processRequest() throwsIOException {
_buffer.clear();
_clientChannel.read(_buffer);int result = _intBuffer.get(0) + _intBuffer.get(1);
_buffer.flip();
_buffer.clear();
_intBuffer.put(0, result);
_clientChannel.write(_buffer);
}public static voidmain(String[] args) {newSumServer().start();
}
}//SumServer
來自 : http://blog.chinaunix.net/uid-24186189-id-2623973.html
總結(jié)
以上是生活随笔為你收集整理的java.io和util的区别_Java NIO与IO的区别和比较的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python—元组
- 下一篇: git 怎么查看合并过来哪些代码_git