Direct buffer copy file through JAVA NIO
/** * 通过JAVA NIO 直接缓冲区拷贝文件(内存映射文件) * * @param sourcePath 源文件路径 * @param targetPath 目标文件路径 */ public static void copyFileByChannelBufferd(String sourcePath, String targetPath) { FileChannel inChannel = null; FileChannel outChannel = null; try { //获取通道,StandardOpenOption.READ表示可读,StandardOpenOption.WRITE表示可写,StandardOpenOption.CREATE表示可以创建 inChannel = FileChannel.open(Paths.get(sourcePath), StandardOpenOption.READ); outChannel = FileChannel.open(Paths.get(targetPath), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE); //创建内存映射文件 MappedByteBuffer inMapped = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size()); MappedByteBuffer outMapped = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size()); //直接操作内存映射文件 byte[] buf = new byte[inMapped.limit()]; inMapped.get(buf); outMapped.put(buf); } catch (IOException e) { e.printStackTrace(); } finally { //关闭流 try { if (outChannel != null) { outChannel.close(); } if (inChannel != null) { inChannel.close(); } } catch (IOException e) { e.printStackTrace(); } } }
The above is the detailed content of How to copy files directly from JAVA NIO buffer. For more information, please follow other related articles on the PHP Chinese website!