NIO支持緩沖區(qū)和通道,效率非常高,非常好用,代碼演示如下 1.NIO的HelloWorld
package cn.zzu.wcj.nio;import static org.junit.Assert.*;import java.nio.ByteBuffer;import org.junit.Test;/* * 一、緩沖區(qū)(Buffer):在 Java NIO 中負(fù)責(zé)數(shù)據(jù)的存取。緩沖區(qū)就是數(shù)組。用于存儲(chǔ)不同數(shù)據(jù)類(lèi)型的數(shù)據(jù) * * 根據(jù)數(shù)據(jù)類(lèi)型不同(boolean 除外),提供了相應(yīng)類(lèi)型的緩沖區(qū): * ByteBuffer * CharBuffer * ShortBuffer * IntBuffer * LongBuffer * FloatBuffer * DoubleBuffer * * 上述緩沖區(qū)的管理方式幾乎一致,通過(guò) allocate() 獲取緩沖區(qū) * * 二、緩沖區(qū)存取數(shù)據(jù)的兩個(gè)核心方法: * put() : 存入數(shù)據(jù)到緩沖區(qū)中 * get() : 獲取緩沖區(qū)中的數(shù)據(jù) * * 三、緩沖區(qū)中的四個(gè)核心屬性: * capacity : 容量,表示緩沖區(qū)中最大存儲(chǔ)數(shù)據(jù)的容量。一旦聲明不能改變。 * limit : 界限,表示緩沖區(qū)中可以操作數(shù)據(jù)的大小。(limit 后數(shù)據(jù)不能進(jìn)行讀寫(xiě)) * position : 位置,表示緩沖區(qū)中正在操作數(shù)據(jù)的位置。 * * mark : 標(biāo)記,表示記錄當(dāng)前 position 的位置。可以通過(guò) reset() 恢復(fù)到 mark 的位置 * * 0 <= mark <= position <= limit <= capacity * * 四、直接緩沖區(qū)與非直接緩沖區(qū): * 非直接緩沖區(qū):通過(guò) allocate() 方法分配緩沖區(qū),將緩沖區(qū)建立在 JVM 的內(nèi)存中 * 直接緩沖區(qū):通過(guò) allocateDirect() 方法分配直接緩沖區(qū),將緩沖區(qū)建立在物理內(nèi)存中。可以提高效率 */public class BufferTest { @Test public void test1() { String str="abcde" ; //1.分配一個(gè)指定大小的緩沖區(qū) ByteBuffer buf=ByteBuffer.allocate(1024) ; System.out.ip() ; System.out.println("-----------------flip()------------------"); System.out.println("position="+buf.position()); System.out.println("limit="+buf.limit()); System.out.println("capacity="+buf.capacity()); //4.利用get()讀取緩沖區(qū)中的數(shù)據(jù) byte[] dst=new byte[buf.limit()] ; buf.get(dst,buf.position(),buf.limit()) ; System.out.println("-----------------get()------------------"); System.out.println("position="+buf.position()); System.out.println("limit="+buf.limit()); System.out.println("capacity="+buf.capacity()); //5.rewind()可重復(fù)讀 buf.rewind() ; System.out.println("-----------------rewind()------------------"); System.out.println("position="+buf.position()); System.out.println("limit="+buf.limit()); System.out.println("capacity="+buf.capacity()); //6.clear():清空緩沖區(qū),但是緩沖區(qū)中的數(shù)據(jù)依然存在,但是處于‘被遺忘’狀態(tài) buf.clear() ; System.out.println("-----------------clear()------------------"); System.out.println("position="+buf.position()); System.out.println("limit="+buf.limit()); System.out.println("capacity="+buf.capacity()); System.out.println((char)buf.get(0)); } @Test public void test2(){ String str="abcde" ; ByteBuffer buf=ByteBuffer.allocate(1024) ; byte[] source=str.getBytes() ; buf.put(source, 0,2) ; System.out.println("position="+buf.position()); buf.mark() ; System.out.println("-------------mark()@2--------------"); buf.put(source, 2, 2) ; System.out.println("position="+buf.position()); System.out.println("----------------reset()--------------------"); buf.reset() ; System.out.println("position="+buf.position());// System.out.println("len="+source.length); if(buf.hasRemaining()){ System.out.println(buf.remaining()); } } @Test public void test3(){ ByteBuffer buf=ByteBuffer.allocateDirect(1024) ; assertSame(true, buf.isDirect()); }}2.創(chuàng)建Channel的幾種方式
package cn.zzu.wcj.nio;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.RandomaccessFile;import java.nio.ByteBuffer;import java.nio.CharBuffer;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.FileChannel.MapMode;import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import java.nio.charset.CharsetEncoder;import java.nio.file.Paths;import java.nio.file.StandardOpenOption;import java.util.Map;import java.util.Map.Entry;import java.util.Set;import org.junit.Test;/* * 一、通道(Channel):用于源節(jié)點(diǎn)與目標(biāo)節(jié)點(diǎn)的連接。在 Java NIO 中負(fù)責(zé)緩沖區(qū)中數(shù)據(jù)的傳輸。Channel 本身不存儲(chǔ)數(shù)據(jù),因此需要配合緩沖區(qū)進(jìn)行傳輸。 * * 二、通道的主要實(shí)現(xiàn)類(lèi) * java.nio.channels.Channel 接口: * |--FileChannel * |--SocketChannel * |--ServerSocketChannel * |--DatagramChannel * * 三、獲取通道 * 1. Java 針對(duì)支持通道的類(lèi)提供了 getChannel() 方法 * 本地 IO: * FileInputStream/FileOutputStream * RandomAccessFile * * 網(wǎng)絡(luò)IO: * Socket * ServerSocket * DatagramSocket * * 2. 在 JDK 1.7 中的 NIO.2 針對(duì)各個(gè)通道提供了靜態(tài)方法 open() * 3. 在 JDK 1.7 中的 NIO.2 的 Files 工具類(lèi)的 newByteChannel() * * 四、通道之間的數(shù)據(jù)傳輸 * transferFrom() * transferTo() * * 五、分散(Scatter)與聚集(Gather) * 分散讀取(Scattering Reads):將通道中的數(shù)據(jù)分散到多個(gè)緩沖區(qū)中 * 聚集寫(xiě)入(Gathering Writes):將多個(gè)緩沖區(qū)中的數(shù)據(jù)聚集到通道中 * * 六、字符集:Charset * 編碼:字符串 -> 字節(jié)數(shù)組 * 解碼:字節(jié)數(shù)組 -> 字符串 * */public class ChannelTest { @Test public void testEncDec() throws Exception{ Charset charset = Charset.forName("GBK") ; CharsetEncoder encoder = charset.newEncoder(); CharsetDecoder decoder = charset.newDecoder() ; CharBuffer charBuf=CharBuffer.allocate(1024) ; charBuf.put("HelloWorld,世界你好!"); charBuf.flip() ; ByteBuffer byteBuffer = encoder.encode(charBuf); for(int x=0;x<byteBuffer.limit();x++){ System.out.print(byteBuffer.get()+"、"); } System.out.println(); byteBuffer.flip() ; CharBuffer charBuffer = decoder.decode(byteBuffer); System.out.println(charBuffer.toString()); System.out.println("-----------------------------");// Charset charset2 = Charset.forName("UTF-8") ; Charset charset2 = Charset.forName("GBK") ; byteBuffer.flip() ; CharBuffer charBuffer2 = charset2.decode(byteBuffer) ; System.out.println(charBuffer2.toString()); } @Test public void testCharset(){ Map<String,Charset> charsets = Charset.availableCharsets() ; Set<Entry<String,Charset>> set = charsets.entrySet() ; for(Entry<String,Charset> e : set ){ System.out.println(e.getKey()+"="+e.getValue()); } } @Test public void testScatterAndGather()throws Exception{ RandomAccessFile raf=new RandomAccessFile("1.txt", "rw") ; FileChannel inChannel = raf.getChannel() ; ByteBuffer buf=ByteBuffer.allocate(100) ; ByteBuffer buf2=ByteBuffer.allocate(1024) ; ByteBuffer bufs[]={buf,buf2} ; inChannel.read(bufs) ; for(ByteBuffer byteBuf : bufs){ byteBuf.flip() ; //切換到讀取模式 } System.out.println(new String(bufs[0].array(),0,bufs[0].limit())); System.out.println("------------------------------------------------"); System.out.println(new String(bufs[1].array(),0,bufs[1].limit())); RandomAccessFile raf2=new RandomAccessFile("2.txt", "rw") ; FileChannel outChannel = raf2.getChannel() ; outChannel.write(bufs) ; outChannel.close(); inChannel.close(); raf.close(); raf2.close(); } @Test public void testChannel() throws Exception{ long start=System.currentTimeMillis() ; FileInputStream fis=null ; FileOutputStream fos=null ; fis=new FileInputStream("1.jpg"); fos=new FileOutputStream("2.jpg") ; //1.獲取通道 FileChannel inChannel = fis.getChannel(); FileChannel outChannel = fos.getChannel(); //2.準(zhǔn)備緩沖區(qū) ByteBuffer buf=ByteBuffer.allocate(1024) ; //3.讀寫(xiě) while(inChannel.read(buf) != -1){ //讀 buf.flip() ; //切換到讀取模式 outChannel.write(buf) ; //寫(xiě) buf.clear() ; //清空緩沖區(qū),準(zhǔn)備再次讀取 } //4.關(guān)閉流 outChannel.close(); inChannel.close(); fos.close(); fis.close(); long end=System.currentTimeMillis() ; System.out.println("拷貝任務(wù)耗時(shí):"+(end-start)+" 毫秒"); } @Test public void testDirectChannel()throws Exception{ long start=System.currentTimeMillis() ; FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ) ; FileChannel outChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE ) ; //內(nèi)存映射文件 MappedByteBuffer inMappedBuf = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size()) ; MappedByteBuffer outMappedBuf = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size()) ; //直接對(duì)緩沖區(qū)中的數(shù)據(jù)進(jìn)行讀寫(xiě)操作 byte[] temp=new byte[1024] ; inMappedBuf.get(temp) ; outMappedBuf.put(temp) ; inChannel.close(); outChannel.close(); long end=System.currentTimeMillis() ; System.out.println("拷貝任務(wù)耗時(shí):"+(end-start)+" 毫秒"); } @Test public void testTransform()throws Exception{ FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ) ; FileChannel outChannel = FileChannel.open(Paths.get("4.jpg"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE ) ; //inChannel.transferTo(0, inChannel.size(), outChannel) ; outChannel.transferFrom(inChannel, 0, inChannel.size()) ; inChannel.close(); outChannel.close(); }}3.阻塞式NIO
package cn.zzu.wcj.nio;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.nio.file.Paths;import java.nio.file.StandardOpenOption;import org.junit.Test;/* * 一、使用 NIO 完成網(wǎng)絡(luò)通信的三個(gè)核心: * * 1. 通道(Channel):負(fù)責(zé)連接 * * java.nio.channels.Channel 接口: * |--SelectableChannel * |--SocketChannel * |--ServerSocketChannel * |--DatagramChannel * * |--Pipe.SinkChannel * |--Pipe.SourceChannel * * 2. 緩沖區(qū)(Buffer):負(fù)責(zé)數(shù)據(jù)的存取 * * 3. 選擇器(Selector):是 SelectableChannel 的多路復(fù)用器。用于監(jiān)控 SelectableChannel 的 IO 狀況 * */public class BlockingNIOTest { @Test public void testClient() throws Exception { //1.創(chuàng)建通道 SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8989)); //2.準(zhǔn)備緩沖區(qū) FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ) ; ByteBuffer buf=ByteBuffer.allocate(1024) ; //3.讀取本地文件,發(fā)送到客戶(hù)端 while(inChannel.read(buf) != -1){ buf.flip() ; socketChannel.write(buf) ; buf.clear() ; } //4.關(guān)閉通道 inChannel.close(); socketChannel.close(); } @Test public void testServer() throws Exception{ //1.創(chuàng)建通道 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open() ; //2.綁定端口號(hào) serverSocketChannel.bind(new InetSocketAddress(8989)) ; //3.準(zhǔn)備Channel和Buffer FileChannel outChannel=FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE) ; ByteBuffer buf=ByteBuffer.allocate(1024) ; //4.接收客戶(hù)端請(qǐng)求 SocketChannel socketChannel = serverSocketChannel.accept() ; while(socketChannel.read(buf) != -1){ buf.flip() ; outChannel.write(buf) ; buf.clear() ; } //5.關(guān)閉流 socketChannel.close(); outChannel.close(); serverSocketChannel.close(); }}package cn.zzu.wcj.nio;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.nio.file.Paths;import java.nio.file.StandardOpenOption;import org.junit.Test;public class BlockingNIOTestPlus { @Test public void testClent() throws Exception{ SocketChannel client = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999)) ; FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ) ; ByteBuffer buf=ByteBuffer.allocate(1024) ; while(inChannel.read(buf) != -1){ buf.flip() ; client.write(buf) ; buf.clear() ; } client.shutdownOutput() ; //結(jié)束輸出 //接收服務(wù)器反饋 while(client.read(buf) != -1){ buf.flip() ; System.out.println(new String(buf.array(),0,buf.limit())); buf.clear() ; } inChannel.close() ; client.close() ; } @Test public void testServer() throws Exception{ ServerSocketChannel server = ServerSocketChannel.open() ; server.bind(new InetSocketAddress(9999)) ; FileChannel outChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE ) ; ByteBuffer buf=ByteBuffer.allocate(1024) ; SocketChannel client = server.accept(); while(client.read(buf)!=-1){ buf.flip() ; outChannel.write(buf) ; buf.clear() ; } //發(fā)送反饋給客戶(hù)端 buf.put("乖?xún)鹤?爸爸接收到黃圖啦!!!".getBytes()) ; buf.flip() ; client.write(buf) ; client.close(); outChannel.close(); server.close(); }}4.非阻塞式NIO
package cn.zzu.wcj.nio;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SelectionKey;import java.nio.channels.Selector;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Iterator;import java.util.Scanner;import org.junit.Test;/* * 一、使用 NIO 完成網(wǎng)絡(luò)通信的三個(gè)核心: * * 1. 通道(Channel):負(fù)責(zé)連接 * * java.nio.channels.Channel 接口: * |--SelectableChannel * |--SocketChannel * |--ServerSocketChannel * |--DatagramChannel * * |--Pipe.SinkChannel * |--Pipe.SourceChannel * * 2. 緩沖區(qū)(Buffer):負(fù)責(zé)數(shù)據(jù)的存取 * * 3. 選擇器(Selector):是 SelectableChannel 的多路復(fù)用器。用于監(jiān)控 SelectableChannel 的 IO 狀況 * */public class TestNonBlockingChannel { @Test public void testClient() throws Exception{ //創(chuàng)建客戶(hù)端通道 SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",6666)) ; //配置為非阻塞式NIO sChannel.configureBlocking(false) ; //準(zhǔn)備緩沖區(qū) ByteBuffer buffer = ByteBuffer.allocate(1024) ; Scanner sc=new Scanner(System.in) ; while(sc.hasNext()){ buffer.put((new Date().toString()+" : "+sc.next()).getBytes()) ; buffer.flip() ; //切換成讀模式 //向服務(wù)器端發(fā)送消息 sChannel.write(buffer) ; buffer.clear() ; } //關(guān)閉通道 sChannel.close(); } @Test public void testServer() throws Exception{ //1.創(chuàng)建服務(wù)器端通道 ServerSocketChannel ssChannel = ServerSocketChannel.open() ; //2.綁定端口號(hào) ssChannel.bind(new InetSocketAddress(6666)) ; //3.設(shè)置非阻塞模式 ssChannel.configureBlocking(false) ; //4.獲取選擇器 Selector selector = Selector.open() ; //5.將選擇器注冊(cè)到通道上 ssChannel.register(selector,SelectionKey.OP_ACCEPT) ; //6.以輪訓(xùn)的方式獲取選擇器上已經(jīng)準(zhǔn)備就緒的事件 while(selector.select() > 0){ //7.接收全部選擇鍵 Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while(iterator.hasNext()){ //8.接收選擇鍵 SelectionKey selectionKey = iterator.next(); //9.根據(jù)鍵值判斷具體是什么事件 if(selectionKey.isAcceptable()){ //10.接收就緒,獲取客戶(hù)端連接 SocketChannel sChannel = ssChannel.accept() ; //11.切換到非阻塞模式 sChannel.configureBlocking(false) ; //12.將通道注冊(cè)到選擇器上 sChannel.register(selector, SelectionKey.OP_READ) ; }else if(selectionKey.isReadable()){ //13.獲取讀狀態(tài)的通道 SocketChannel sChannel=(SocketChannel) selectionKey.channel() ; ByteBuffer dst=ByteBuffer.allocate(1024) ; //14.讀取數(shù)據(jù) Integer length=0 ; while( (length=sChannel.read(dst))> 0){ dst.flip() ; System.out.println(new String(dst.array(),0,length)); dst.clear() ; } } //15.取消選擇鍵 iterator.remove(); } } }}package cn.zzu.wcj.nio;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.DatagramChannel;import java.nio.channels.SelectionKey;import java.nio.channels.Selector;import java.util.Date;import java.util.Iterator;import java.util.Scanner;import org.junit.Test;public class TestNonBlockingNIOPlus { @Test public void testSend() throws Exception{ DatagramChannel dc=DatagramChannel.open() ; dc.configureBlocking(false) ; ByteBuffer buf=ByteBuffer.allocate(1024) ; Scanner sc=new Scanner(System.in) ; while(sc.hasNext()){ String msg=sc.next() ; buf.put((new Date().toString()+" : "+msg).getBytes()) ; buf.flip() ; dc.send(buf, new InetSocketAddress("127.0.0.1",9999)) ; buf.clear() ; } dc.close(); } @Test public void testReceive() throws Exception{ DatagramChannel dc = DatagramChannel.open() ; dc.configureBlocking(false) ; dc.bind(new InetSocketAddress(9999)) ; Selector selector = Selector.open() ; dc.register(selector, SelectionKey.OP_READ) ; while(selector.select()>0){ Iterator<SelectionKey> iterator = selector.selectedKeys().iterator() ; while(iterator.hasNext()){ SelectionKey selectionKey = iterator.next(); if(selectionKey.isReadable()){ ByteBuffer buf=ByteBuffer.allocate(1024) ; dc.receive(buf) ; buf.flip() ; System.out.println(new String(buf.array(),0,buf.limit())); buf.clear() ; } } iterator.remove(); } }}5.管道
package cn.zzu.wcj.nio;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.Pipe;import java.nio.channels.Pipe.SinkChannel;import java.nio.channels.Pipe.SourceChannel;import org.junit.Test;public class PipeTest { @Test public void testPipe() throws Exception{ //1.獲取管道 Pipe pipe = Pipe.open() ; SinkChannel sinkChannel = pipe.sink(); //2.準(zhǔn)備緩沖區(qū) ByteBuffer buf=ByteBuffer.allocate(1024) ; buf.put("單向管道發(fā)送數(shù)據(jù)".getBytes()) ; buf.flip() ; //4.發(fā)送數(shù)據(jù) sinkChannel.write(buf) ; buf.clear() ; //5.接收數(shù)據(jù) SourceChannel sourceChannel = pipe.source() ; sourceChannel.read(buf) ; buf.flip() ; System.out.println(new String(buf.array(),0,buf.limit())); }}新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注