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

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

Java高級編程-NIO

2019-11-14 09:30: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
久久成人18免费网站| 欧美一区二区三区……| 中文字幕精品www乱入免费视频| 日韩精品丝袜在线| 亚洲电影av在线| 91精品国产高清自在线| 欧美性猛交xxxx乱大交极品| 日韩欧美亚洲一二三区| 午夜精品久久久久久久男人的天堂| 亚洲影视九九影院在线观看| 国产亚洲欧美日韩美女| 日本亚洲欧美成人| 日韩av免费观影| 欧美另类xxx| 国产精品私拍pans大尺度在线| 亚洲高清在线观看| 成人av资源在线播放| 日本19禁啪啪免费观看www| 成人免费福利视频| 国产精品久久久久91| 欧美成人精品xxx| 色www亚洲国产张柏芝| 欧美又大又粗又长| 川上优av一区二区线观看| 日韩欧美国产高清91| 欧美色播在线播放| 日韩精品在线观看一区二区| 亚洲人成亚洲人成在线观看| 青青草99啪国产免费| 欧美性受xxxx黑人猛交| 欧美色道久久88综合亚洲精品| 国产精品一区专区欧美日韩| 国产日韩欧美在线看| 国产99久久精品一区二区 夜夜躁日日躁| 欧美日韩成人精品| 92版电视剧仙鹤神针在线观看| 亚洲偷熟乱区亚洲香蕉av| 欧美在线视频网站| 成人免费在线视频网站| 日韩精品亚洲精品| 日韩av在线一区二区| 亚洲一区亚洲二区| 亚洲男人的天堂在线播放| 国产精品久久久久久av福利| 国产精品jvid在线观看蜜臀| 国产日韩中文在线| 国产成人精品电影| 亚洲小视频在线| 欧美精品在线播放| 国产精品白嫩美女在线观看| 亚洲国产97在线精品一区| 亚洲成年人在线播放| 日本精品一区二区三区在线播放视频| 日韩激情av在线免费观看| 国产在线播放91| 久久99国产综合精品女同| 国产成人免费av电影| 日本欧美一级片| 国产欧美精品久久久| 亚洲欧美日韩在线高清直播| 欧美在线精品免播放器视频| 亚洲精品综合久久中文字幕| 国模吧一区二区三区| 精品国产91久久久久久老师| 色与欲影视天天看综合网| 欧美日韩精品在线观看| 91国产视频在线播放| 亚洲性夜色噜噜噜7777| 国产精品都在这里| 久久躁日日躁aaaaxxxx| 亚洲最大福利网站| 精品国产鲁一鲁一区二区张丽| 一区二区三区回区在观看免费视频| 国产精品揄拍一区二区| 国产精品一区av| 欧美日韩精品在线播放| 久久人人爽人人爽人人片av高清| 8090成年在线看片午夜| 亚洲自拍高清视频网站| 欧美激情xxxx| 国产视频久久久| 一区二区三区四区在线观看视频| 正在播放国产一区| 日韩在线免费av| 中文字幕日韩综合av| 性欧美视频videos6一9| 久久不射热爱视频精品| 国产精品女人网站| 久久99亚洲热视| 成人国产精品久久久久久亚洲| 日韩中文字幕在线看| 久久精品国产一区| 精品久久久久久久久久久久久久| 日韩三级影视基地| 欧美性xxxxxxxxx| 亚洲一区二区三| 91视频免费网站| 欧美激情乱人伦一区| 91精品国产色综合久久不卡98| 亚洲国产精品资源| 欧美精品在线网站| 久久天天躁狠狠躁夜夜爽蜜月| 国产一区私人高清影院| 亚洲人精品午夜在线观看| 91精品国产高清久久久久久91| 欧美精品电影在线| 欧美成人精品h版在线观看| 久久91精品国产91久久跳| 国产免费一区二区三区香蕉精| 亚洲视频欧美视频| 九九久久综合网站| 久久久99免费视频| 日韩欧美a级成人黄色| 欧美限制级电影在线观看| 欧美日韩性视频在线| 久久影视电视剧免费网站清宫辞电视| 国产成人综合精品在线| 国产亚洲精品一区二555| 国产精品一二区| 日韩女优在线播放| 成人a免费视频| 亚洲欧美另类国产| 久久精品男人天堂| 91在线观看欧美日韩| 91精品久久久久久久久久| 日本午夜精品理论片a级appf发布| 在线观看91久久久久久| 岛国av一区二区在线在线观看| 精品欧美国产一区二区三区| 亚洲国产高潮在线观看| 欧美猛交免费看| 欧美老女人xx| 久久人人爽人人爽人人片亚洲| 日韩欧美aⅴ综合网站发布| 欧美激情视频在线观看| 国产精品1区2区在线观看| 国产精品私拍pans大尺度在线| 亚洲精品www| 亚洲午夜性刺激影院| 欧美肥臀大乳一区二区免费视频| 亚洲人午夜色婷婷| 日韩视频免费大全中文字幕| 欧美亚州一区二区三区| 亚洲综合在线播放| 国产精品一区二区性色av| 成人国产精品一区二区| 美女av一区二区三区| 日韩美女在线观看| 欧美特黄级在线| 欧美黑人xxxⅹ高潮交| 搡老女人一区二区三区视频tv| 欧美激情va永久在线播放| 精品视频一区在线视频| 久久综合伊人77777蜜臀| 亚洲va欧美va国产综合久久| 欧美色视频日本版| 中文字幕在线国产精品| 北条麻妃99精品青青久久| 欧美一级bbbbb性bbbb喷潮片| 国产精品三级网站| 国产精品久久久久99| 中文字幕免费国产精品| 国产精品吴梦梦| 久久久久久久久久久国产|