亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 學院 > 開發設計 > 正文

Java高級編程-NIO

2019-11-14 08:54:53
字體:
來源:轉載
供稿:網友

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.accessFile;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) * 分散讀?。⊿cattering 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())); }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
久久久女女女女999久久| 91精品国产九九九久久久亚洲| 中文字幕亚洲欧美日韩在线不卡| 日韩av一卡二卡| 911国产网站尤物在线观看| 欧美日韩福利在线观看| 最近2019中文字幕在线高清| 久久久www成人免费精品张筱雨| 91精品在线国产| 日韩中文有码在线视频| 亚洲精选中文字幕| 成人激情视频小说免费下载| 久久综合九色九九| 亚洲mm色国产网站| 亚洲成人国产精品| 91夜夜未满十八勿入爽爽影院| 青青在线视频一区二区三区| 成人精品久久久| 亚洲精品电影网| 午夜精品一区二区三区在线| 国产欧美日韩中文| 国产亚洲欧美一区| 91精品在线观看视频| 国产精品免费久久久| 日韩精品中文字| 欧美日韩综合视频| 国产精品高清免费在线观看| 成人www视频在线观看| 欧美性生交xxxxxdddd| 欧美日韩亚洲一区二区| 久久久久久高潮国产精品视| 日韩女优人人人人射在线视频| 日本精品一区二区三区在线| 欧美尺度大的性做爰视频| 日韩美女av在线| 欧美老少配视频| 久久精品视频在线| 欧美最猛性xxxxx亚洲精品| 亚洲美女免费精品视频在线观看| 国内偷自视频区视频综合| 国产精品精品久久久久久| 成人免费淫片aa视频免费| 日韩视频在线免费观看| 成人在线免费观看视视频| 欧美在线免费视频| 91av国产在线| 成人网页在线免费观看| 国产在线98福利播放视频| 亚洲精品成人av| 国产欧美亚洲视频| 亚洲国产精品专区久久| 亚洲精品v天堂中文字幕| 91中文精品字幕在线视频| 国产亚洲精品久久久久久777| 久久这里只有精品视频首页| 国产精品久久久一区| 日韩一区二区福利| 成人免费网视频| 欧美日韩亚洲视频| 97免费视频在线播放| 精品久久久久久久久中文字幕| 亚洲欧美中文日韩在线| 国产精品av免费在线观看| 欧美整片在线观看| 亚洲激情视频网| 久99九色视频在线观看| 欧美日韩激情美女| 美女久久久久久久久久久| 97超碰国产精品女人人人爽| 91在线直播亚洲| 精品日本美女福利在线观看| 成人国产精品日本在线| 欧美限制级电影在线观看| 国产精品午夜国产小视频| 2019av中文字幕| 亚洲午夜精品视频| 国内精品久久久久久久| 亚洲欧美国产高清va在线播| 日韩在线播放一区| 九九热在线精品视频| 亚洲第一精品自拍| 欧美激情精品久久久久久大尺度| 成人日韩在线电影| 992tv在线成人免费观看| 国产精品国产三级国产aⅴ浪潮| 久久av资源网站| 国产一区私人高清影院| 国产精品久久久久久av福利| 国模精品视频一区二区| 日韩精品中文字幕视频在线| 狠狠躁夜夜躁人人躁婷婷91| 97久久超碰福利国产精品…| 久久人人97超碰精品888| 国产精品久久电影观看| 国产成人97精品免费看片| 精品福利一区二区| 国产精品人人做人人爽| 国产福利精品av综合导导航| 欧美做受高潮电影o| 欧美精品电影免费在线观看| 欧美精品激情在线| 在线看片第一页欧美| 国产精品一区二区久久精品| 亚洲电影免费观看高清| 亚洲一区国产精品| 欧美中文字幕在线播放| 91亚洲永久免费精品| 中文字幕日韩av综合精品| 亚洲成人在线网| 久久久久久久久久久免费| 日韩黄在线观看| 久久久亚洲国产天美传媒修理工| 欧美自拍视频在线| 日韩电视剧免费观看网站| 奇米4444一区二区三区| 国产精品一区二区久久| 91精品久久久久久久久不口人| 在线一区二区日韩| 亚洲国产精品大全| 国产精品男女猛烈高潮激情| 欧美性极品xxxx做受| 国产精品欧美风情| 国语自产精品视频在线看抢先版图片| 欧美激情一二三| 欧美日韩一区二区在线| 国产中文字幕91| 91成人天堂久久成人| 亚洲欧美日韩天堂一区二区| 在线不卡国产精品| 夜夜嗨av一区二区三区免费区| 国模视频一区二区| 亚洲伊人成综合成人网| 91精品国产91久久久久| 欧美不卡视频一区发布| 久久九九全国免费精品观看| 国产精品亚洲精品| 91亚洲精品一区| 日韩高清免费在线| 日韩欧美亚洲范冰冰与中字| 亚洲欧洲日韩国产| 国产精品情侣自拍| 视频直播国产精品| 久久久亚洲天堂| 国产精品福利在线观看网址| 日韩免费不卡av| 69av视频在线播放| 亚洲电影第1页| 欧美日韩激情视频8区| 国产亚洲在线播放| 91在线网站视频| 久久久精品一区二区三区| 久久久最新网址| 精品亚洲一区二区三区在线播放| 亚洲国产精品久久精品怡红院| 高清欧美一区二区三区| 欧美性videos高清精品| 欧美另类高清videos| 国模视频一区二区| 中文字幕亚洲一区| 国产美女搞久久| 亚洲欧美成人网| 亚洲欧洲日产国码av系列天堂| 欧美亚洲另类视频| 国产91精品高潮白浆喷水|