NIO(四)
阿新 • • 發佈:2018-11-29
使用直接緩衝區完成檔案的複製(記憶體對映檔案)
package com.cppdy.nio; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; //使用直接緩衝區完成檔案的複製(記憶體對映檔案) public class NIOBufferDemo2 { publicstatic void main(String[] args) throws Exception { //直接緩衝區 FileChannel inChannel = FileChannel.open(Paths.get("F:\\cppdy\\1.jpg"), StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("F:\\cppdy\\2.jpg"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);//緩衝區 MappedByteBuffer inMap = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size()); MappedByteBuffer outMap = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size()); //直接對緩衝區進行資料讀寫操作 byte[] bytes=new byte[inMap.limit()]; inMap.get(bytes); outMap.put(bytes); outMap.clear(); System.out.println("複製完畢"); } }