这篇文章主要为大家展示了“如何通过JAVA NIO直接缓冲区拷贝文件”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何通过JAVA NIO直接缓冲区拷贝文件”这篇文章吧。
通过JAVA NIO 直接缓冲区拷贝文件
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(); } } }
以上是“如何通过JAVA NIO直接缓冲区拷贝文件”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网行业资讯频道!