java NIO中的channel、分散、聚集(二)
阿新 • • 發佈:2018-12-10
Java NIO中的通道(channel)介紹、通道的實現方式、直接緩衝區和非直接緩衝區、nio中的分散聚集。
/** * * * 一.通道(channel):用於源節點和目標節點的連線。在Java nio中負責資料的傳輸, * channel本身不儲存資料,因此需要配合緩衝區進行傳輸。 * * 寫資料到Buffer有兩種方式: 從Channel寫到Buffer。 int bytesRead = inChannel.read(buf); //read into buffer. 通過Buffer的put()方法寫到Buffer裡。 buf.put(127); 從Buffer中讀取資料有兩種方式: 從Buffer讀取資料到Channel。 int bytesWritten = inChannel.write(buf); 使用get()方法從Buffer中讀取資料。 byte aByte = buf.get(); * 二.通道的主要實現類: * java.nio.channels.Channel介面: * |--FileChanel 檔案通道,本地通道 * |--SocketChannel 網路io * |--ServerSocketChannel 網路io * |--DatagramChannel UDP 網路io * * 三.獲取通道 三種方式 * 1.Java針對支援通道的類提供了getChannel()方法,獲取對應的通道 * 本地IO: * FileInputStream/FileOutputStream * RandomAccessFile * * 網路IO * Socket * ServerSocket * DatagramSocket * * 2.jdk1.7中的在NIO2中針對各個通道提供了靜態方法open() * 3.jdk1.7中的NIO2中的Files 工具類的newByteChannel() * * 四、通道之間的資料傳輸 * transferFrom() * transferTo() * * 五、分散和聚集 * 分散讀取:將通道中的資料分散到多個緩衝區 * 聚集寫入:將多個緩衝區中的資料聚集到通道中 * * 六、字符集Charset * 編碼:字串轉成位元組陣列 * 解碼:位元組陣列轉成字串 */ public class ChannelTest { /** * 1利用通道完成檔案的複製 * 非直接緩衝區 * @throws IOException */ @Test public void copy1() throws IOException { long start = System.currentTimeMillis(); //2.獲取通道 FileChannel inChannel= null; FileChannel outChannel= null; // FileInputStream fis = new FileInputStream("1.jpg"); // FileOutputStream fos = new FileOutputStream("2.jpg"); FileInputStream fis = new FileInputStream("d:/1.rar"); FileOutputStream fos = new FileOutputStream("d:/2.rar"); inChannel = fis.getChannel(); outChannel = fos.getChannel(); //3分配指定大小的緩衝區 ByteBuffer buf = ByteBuffer.allocate(1024); //4將通道中的資料存入緩衝區 while (inChannel.read(buf) != -1) { buf.flip(); //切換成讀取資料的模式 //將緩衝區中的資料寫入通道中 outChannel.write(buf); buf.clear();//清空緩衝區 } System.out.println("耗時:"+(System.currentTimeMillis() - start)); } /** * 使用直接緩衝區 完成檔案的複製(記憶體對映檔案(直接緩衝區)) */ @Test public void copy2() { long start = System.currentTimeMillis(); try { //Paths.get("d:/","a/")可變引數,可以拼接地址 // FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"),StandardOpenOption.READ); // FileChannel outChannel = FileChannel.open(Paths.get("3.jpg"),StandardOpenOption.READ, // StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW);//CREATE 建立,如果有就覆蓋 CREATE_NEW 建立,如果有就報錯 FileChannel inChannel = FileChannel.open(Paths.get("d:/","1.rar"),StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("d:/","2.rar"),StandardOpenOption.READ, StandardOpenOption.WRITE,StandardOpenOption.CREATE);//CREATE 建立,如果有就覆蓋 CREATE_NEW 建立,如果有就報錯 //記憶體對映檔案(直接緩衝區) //ByteBuffer.allocateDirect(capacity) MappedByteBuffer inMapBuffer = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size()); MappedByteBuffer outMapBuffer = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size()); //直接對緩衝區進行資料的讀寫操作 byte[] dst = new byte[inMapBuffer.limit()]; inMapBuffer.get(dst); outMapBuffer.put(dst); inChannel.close(); outChannel.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("耗時:"+(System.currentTimeMillis() - start)); } /** * 通道之間的資料傳輸 * transferTo() transferFrom() */ @Test public void copy3() { long start = System.currentTimeMillis(); try { FileChannel inChannel = FileChannel.open(Paths.get("d:/1.rar"),StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("d:/2.rar"),StandardOpenOption.READ, StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW);//CREATE 建立,如果有就覆蓋 CREATE_NEW 建立,如果有就報錯 inChannel.transferTo(0, inChannel.size(), outChannel); // outChannel.transferFrom(inChannel, 0, inChannel.size()); outChannel.close(); inChannel.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("耗時:"+(System.currentTimeMillis() - start)); } /** * 分散與聚集 */ @Test public void scatterGather() { try { RandomAccessFile raf = new RandomAccessFile("1.txt", "rw");//讀寫模式 //獲取通道 FileChannel channel1 = raf.getChannel(); //分配指定大小的緩衝區 ByteBuffer buf1 = ByteBuffer.allocate(100); ByteBuffer buf2 = ByteBuffer.allocate(1024); //分散讀取 ByteBuffer[] dsts = {buf1,buf2}; channel1.read(dsts); for (ByteBuffer byteBuffer : dsts) { byteBuffer.flip(); } System.out.println(new String(dsts[0].array(), 0, dsts[0].limit())); System.out.println("--------------------------------------------"); System.out.println(new String(dsts[1].array(), 0, dsts[1].limit())); //聚集寫入 RandomAccessFile raf1 = new RandomAccessFile("2.txt", "rw"); FileChannel channel2 = raf1.getChannel(); channel2.write(dsts); channel2.close(); channel1.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 獲取所有字符集 * 2018年7月24日 */ @Test public void getCharset(){ SortedMap<String, Charset> map = Charset.availableCharsets(); for (Map.Entry<String, Charset> entry : map.entrySet()) { System.out.println(entry.getKey()+"=="+entry.getValue()); } } /** * 編碼解碼 */ @Test public void encoderDecode(){ try { Charset charset = Charset.forName("GBK"); //獲取編碼器 CharsetEncoder newEncoder = charset.newEncoder(); //獲取解碼器 CharsetDecoder newDecoder = charset.newDecoder(); CharBuffer charBuffer = CharBuffer.allocate(1024); charBuffer.put("你好!"); charBuffer.flip(); //編碼 ByteBuffer byteBuffer = newEncoder.encode(charBuffer); for (int i = 0; i <10; i++) { System.out.println(byteBuffer.get()); } byteBuffer.flip(); //解碼 CharBuffer charBuffer2 = newDecoder.decode(byteBuffer); System.out.println(charBuffer2.toString()); } catch (CharacterCodingException e) { e.printStackTrace(); } } }