通过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(); } } }
以上就是如何通过java nio直接缓冲区拷贝文件的详细内容。