NIO支持緩沖區和通道,效率非常高,非常好用,代碼演示如下 1.NIO的HelloWorld
package cn.zzu.wcj.nio;import static org.junit.Assert.*;import java.nio.ByteBuffer;import org.junit.Test;/* * 一、緩沖區(Buffer):在 Java NIO 中負責數據的存取。緩沖區就是數組。用于存儲不同數據類型的數據 * * 根據數據類型不同(boolean 除外),提供了相應類型的緩沖區: * ByteBuffer * CharBuffer * ShortBuffer * IntBuffer * LongBuffer * FloatBuffer * DoubleBuffer * * 上述緩沖區的管理方式幾乎一致,通過 allocate() 獲取緩沖區 * * 二、緩沖區存取數據的兩個核心方法: * put() : 存入數據到緩沖區中 * get() : 獲取緩沖區中的數據 * * 三、緩沖區中的四個核心屬性: * capacity : 容量,表示緩沖區中最大存儲數據的容量。一旦聲明不能改變。 * limit : 界限,表示緩沖區中可以操作數據的大小。(limit 后數據不能進行讀寫) * position : 位置,表示緩沖區中正在操作數據的位置。 * * mark : 標記,表示記錄當前 position 的位置。可以通過 reset() 恢復到 mark 的位置 * * 0 <= mark <= position <= limit <= capacity * * 四、直接緩沖區與非直接緩沖區: * 非直接緩沖區:通過 allocate() 方法分配緩沖區,將緩沖區建立在 JVM 的內存中 * 直接緩沖區:通過 allocateDirect() 方法分配直接緩沖區,將緩沖區建立在物理內存中。可以提高效率 */public class BufferTest { @Test public void test1() { String str="abcde" ; //1.分配一個指定大小的緩沖區 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()讀取緩沖區中的數據 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()可重復讀 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():清空緩沖區,但是緩沖區中的數據依然存在,但是處于‘被遺忘’狀態 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.創建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):用于源節點與目標節點的連接。在 Java NIO 中負責緩沖區中數據的傳輸。Channel 本身不存儲數據,因此需要配合緩沖區進行傳輸。 * * 二、通道的主要實現類 * java.nio.channels.Channel 接口: * |--FileChannel * |--SocketChannel * |--ServerSocketChannel * |--DatagramChannel * * 三、獲取通道 * 1. Java 針對支持通道的類提供了 getChannel() 方法 * 本地 IO: * FileInputStream/FileOutputStream * RandomAccessFile * * 網絡IO: * Socket * ServerSocket * DatagramSocket * * 2. 在 JDK 1.7 中的 NIO.2 針對各個通道提供了靜態方法 open() * 3. 在 JDK 1.7 中的 NIO.2 的 Files 工具類的 newByteChannel() * * 四、通道之間的數據傳輸 * transferFrom() * transferTo() * * 五、分散(Scatter)與聚集(Gather) * 分散讀取(Scattering Reads):將通道中的數據分散到多個緩沖區中 * 聚集寫入(Gathering Writes):將多個緩沖區中的數據聚集到通道中 * * 六、字符集:Charset * 編碼:字符串 -> 字節數組 * 解碼:字節數組 -> 字符串 * */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.準備緩沖區 ByteBuffer buf=ByteBuffer.allocate(1024) ; //3.讀寫 while(inChannel.read(buf) != -1){ //讀 buf.flip() ; //切換到讀取模式 outChannel.write(buf) ; //寫 buf.clear() ; //清空緩沖區,準備再次讀取 } //4.關閉流 outChannel.close(); inChannel.close(); fos.close(); fis.close(); long end=System.currentTimeMillis() ; System.out.println("拷貝任務耗時:"+(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 ) ; //內存映射文件 MappedByteBuffer inMappedBuf = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size()) ; MappedByteBuffer outMappedBuf = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size()) ; //直接對緩沖區中的數據進行讀寫操作 byte[] temp=new byte[1024] ; inMappedBuf.get(temp) ; outMappedBuf.put(temp) ; inChannel.close(); outChannel.close(); long end=System.currentTimeMillis() ; System.out.println("拷貝任務耗時:"+(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 完成網絡通信的三個核心: * * 1. 通道(Channel):負責連接 * * java.nio.channels.Channel 接口: * |--SelectableChannel * |--SocketChannel * |--ServerSocketChannel * |--DatagramChannel * * |--Pipe.SinkChannel * |--Pipe.SourceChannel * * 2. 緩沖區(Buffer):負責數據的存取 * * 3. 選擇器(Selector):是 SelectableChannel 的多路復用器。用于監控 SelectableChannel 的 IO 狀況 * */public class BlockingNIOTest { @Test public void testClient() throws Exception { //1.創建通道 SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8989)); //2.準備緩沖區 FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ) ; ByteBuffer buf=ByteBuffer.allocate(1024) ; //3.讀取本地文件,發送到客戶端 while(inChannel.read(buf) != -1){ buf.flip() ; socketChannel.write(buf) ; buf.clear() ; } //4.關閉通道 inChannel.close(); socketChannel.close(); } @Test public void testServer() throws Exception{ //1.創建通道 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open() ; //2.綁定端口號 serverSocketChannel.bind(new InetSocketAddress(8989)) ; //3.準備Channel和Buffer FileChannel outChannel=FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE) ; ByteBuffer buf=ByteBuffer.allocate(1024) ; //4.接收客戶端請求 SocketChannel socketChannel = serverSocketChannel.accept() ; while(socketChannel.read(buf) != -1){ buf.flip() ; outChannel.write(buf) ; buf.clear() ; } //5.關閉流 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() ; //結束輸出 //接收服務器反饋 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() ; } //發送反饋給客戶端 buf.put("乖兒子,爸爸接收到黃圖啦!!!".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 完成網絡通信的三個核心: * * 1. 通道(Channel):負責連接 * * java.nio.channels.Channel 接口: * |--SelectableChannel * |--SocketChannel * |--ServerSocketChannel * |--DatagramChannel * * |--Pipe.SinkChannel * |--Pipe.SourceChannel * * 2. 緩沖區(Buffer):負責數據的存取 * * 3. 選擇器(Selector):是 SelectableChannel 的多路復用器。用于監控 SelectableChannel 的 IO 狀況 * */public class TestNonBlockingChannel { @Test public void testClient() throws Exception{ //創建客戶端通道 SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",6666)) ; //配置為非阻塞式NIO sChannel.configureBlocking(false) ; //準備緩沖區 ByteBuffer buffer = ByteBuffer.allocate(1024) ; Scanner sc=new Scanner(System.in) ; while(sc.hasNext()){ buffer.put((new Date().toString()+" : "+sc.next()).getBytes()) ; buffer.flip() ; //切換成讀模式 //向服務器端發送消息 sChannel.write(buffer) ; buffer.clear() ; } //關閉通道 sChannel.close(); } @Test public void testServer() throws Exception{ //1.創建服務器端通道 ServerSocketChannel ssChannel = ServerSocketChannel.open() ; //2.綁定端口號 ssChannel.bind(new InetSocketAddress(6666)) ; //3.設置非阻塞模式 ssChannel.configureBlocking(false) ; //4.獲取選擇器 Selector selector = Selector.open() ; //5.將選擇器注冊到通道上 ssChannel.register(selector,SelectionKey.OP_ACCEPT) ; //6.以輪訓的方式獲取選擇器上已經準備就緒的事件 while(selector.select() > 0){ //7.接收全部選擇鍵 Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while(iterator.hasNext()){ //8.接收選擇鍵 SelectionKey selectionKey = iterator.next(); //9.根據鍵值判斷具體是什么事件 if(selectionKey.isAcceptable()){ //10.接收就緒,獲取客戶端連接 SocketChannel sChannel = ssChannel.accept() ; //11.切換到非阻塞模式 sChannel.configureBlocking(false) ; //12.將通道注冊到選擇器上 sChannel.register(selector, SelectionKey.OP_READ) ; }else if(selectionKey.isReadable()){ //13.獲取讀狀態的通道 SocketChannel sChannel=(SocketChannel) selectionKey.channel() ; ByteBuffer dst=ByteBuffer.allocate(1024) ; //14.讀取數據 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.準備緩沖區 ByteBuffer buf=ByteBuffer.allocate(1024) ; buf.put("單向管道發送數據".getBytes()) ; buf.flip() ; //4.發送數據 sinkChannel.write(buf) ; buf.clear() ; //5.接收數據 SourceChannel sourceChannel = pipe.source() ; sourceChannel.read(buf) ; buf.flip() ; System.out.println(new String(buf.array(),0,buf.limit())); }}新聞熱點
疑難解答