NIO的兩種基本實現方式
阿新 • • 發佈:2020-08-07
1. 利用通道完成檔案的複製(非直接緩衝區)
@Test public void test1(){ FileInputStream fis = null; FileOutputStream fos = null; FileChannel inChannel = null; FileChannel outChannel = null; try { fis = new FileInputStream("1.jpg"); fos = new FileOutputStream("2.jpg");//獲取通道 inChannel = fis.getChannel(); outChannel = fos.getChannel(); //分配製定大小的緩衝區 ByteBuffer buf = ByteBuffer.allocate(1024); //將通道中的資料存入緩衝區中 while (inChannel.read(buf) != -1){ //切換為讀取資料的模式 buf.flip();//將緩衝區中的資料寫入通道 outChannel.write(buf); buf.clear(); } } catch (IOException e) { e.printStackTrace(); } finally { if (outChannel != null){ try { outChannel.close(); } catch(IOException e) { e.printStackTrace(); } } if (inChannel != null){ try { inChannel.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
2. 使用直接緩衝區完成檔案的複製(記憶體對映檔案)
@Test public void test2() throws IOException{ 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); //記憶體對映檔案 MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size()); MappedByteBuffer outMappedBuf = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size()); //直接對緩衝區進行資料的讀寫操作 byte[] dst = new byte[inMappedBuf.limit()]; inMappedBuf.get(dst); outMappedBuf.put(dst); inChannel.close(); outChannel.close(); }
第二種方式速度更快,因為通過管道獲取的緩衝區直接對應著實體記憶體,不再建立流物件和新的緩衝區。