1.BIO與NIO的區(qū)別
BIO為阻塞IO,NIO為非阻塞IO。
BIO | NIO |
---|---|
JAVA1.4之前 | Java 1.4之后 |
面向流:以byte為單位處理數(shù)據(jù) | 面向塊:以塊為單位處理數(shù)據(jù) |
同步阻塞 | 同步非阻塞 |
無 | 選擇器(Selector) |
1.1NIO的核心組成部分
Channels
Channel是雙向的,既能做讀操作也能做寫操作,常見Channel如下:
Channel類 | 功能 |
---|---|
FileChannel | 文件數(shù)據(jù)讀寫 |
DtagramChannel | UDP數(shù)據(jù)讀寫 |
ServerScoketChannel和SocketChannel | TCP數(shù)據(jù)讀寫 |
Buffers
緩沖區(qū)Selectors
選擇器,用于監(jiān)聽多個(gè)通道的事件,可實(shí)現(xiàn)單個(gè)線程就可以監(jiān)聽多個(gè)客戶端通道。
2.Channel
Channel封裝了對(duì)數(shù)據(jù)源的操作,可以操作多種數(shù)據(jù)源,但是不必關(guān)心數(shù)據(jù)源的具體物理結(jié)構(gòu)。Channel用于在字節(jié)緩沖區(qū)和另一側(cè)的實(shí)體之間有效地傳輸數(shù)據(jù)。
Channel所有數(shù)據(jù)都是通過Buffer對(duì)象進(jìn)行處理,通道要么讀數(shù)據(jù)到緩沖區(qū),要么從緩沖區(qū)寫入到通道。
public interface Channle extend Closeable { public boolean isOpen(); public void close() throws IOException;}
2.1 FileChannel
FileChannel常用方法如下;
方法名 | 作用 |
---|---|
public int read(ByteBuffer dst) | 從通道讀取數(shù)據(jù)并放到緩沖區(qū)中 |
public int write(ByteBuffer src) | 把緩沖區(qū)的數(shù)據(jù)寫到通道中 |
public long transferFrom(ReadableByteChannel src, long position, long count) | 從目標(biāo)通道中復(fù)制數(shù)據(jù)到當(dāng)前通道 |
public long transferTo(long position, long count, WritableByteChannel target) | 把數(shù)據(jù)從當(dāng)前通道復(fù)制給目標(biāo)通道 |
無法直接打開一個(gè)FileChannel,常見的方法是通過inPutStream和outPutStream或RandomAccessFile獲取一個(gè)FileChannel實(shí)例。
示例代碼
文件寫入示例
package com.hero.nio.file;import org.junit.Test;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;//通過NIO實(shí)現(xiàn)文件IOpublic class TestNIO {@Test //往本地文件中寫數(shù)據(jù)public void test1() throws Exception{ //1. 創(chuàng)建輸出流 FileOutputStream fos=new FileOutputStream("basic.txt"); //2. 從流中得到一個(gè)通道 FileChannel fc=fos.getChannel(); //3. 提供一個(gè)緩沖區(qū) ByteBuffer buffer=ByteBuffer.allocate(1024); //4. 往緩沖區(qū)中存入數(shù)據(jù) String str="HelloJava"; buffer.put(str.getBytes()); //5. 翻轉(zhuǎn)緩沖區(qū) buffer.flip(); while(buffer.hasRemaining()) { //6. 把緩沖區(qū)寫到通道中 fc.write(buffer); } //7. 關(guān)閉 fos.close(); }}
文章來源:http://www.zghlxwxcb.cn/news/detail-823065.html
文件復(fù)制示例文章來源地址http://www.zghlxwxcb.cn/news/detail-823065.html
public void test4() throws Exception { //1. 創(chuàng)建兩個(gè)流 FileInputStream fis = new FileInputStream("basic2.txt"); FileOutputStream fos = new FileOutputStream("basic3.txt"); //2. 得到兩個(gè)通道 FileChannel sourceFC = fis.getChannel(); FileChannel destFC = fos.getChannel(); //3. 復(fù)制 destFC.transferFrom(sourceFC, 0, sourceFC.size()); //4. 關(guān)閉 fis.close(); fos.close();}
到了這里,關(guān)于Java NIO FileChannel:BIO與NIO區(qū)別、核心組成部分和常用方方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!