package com.example.demo.controller.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; /** * 时间: 2018/5/10. * * @author zwf */ public class NioTest { public static void main(String[] args) throws IOException { String sourcePath = "D:\\报表\\111.txt"; String path1 = "D:\\报表\\222.txt"; nioBufferCopy(sourcePath,path1); } private static void nioBufferCopy(String sourcePath,String path) throws IOException { //文件1 File file1 = new File(sourcePath); //文件2 File file2 = new File(path); if (!file2.exists()){ file2.createNewFile(); } //文件输入流 FileInputStream fis = new FileInputStream(file1); //文件输出流 FileOutputStream fos = new FileOutputStream(file2); //获取文件输入流的通道 FileChannel sourceCh = fis.getChannel(); //获取文件输出流的通道,两个类型同样,说明通道能够是双向的 FileChannel destCh = fos.getChannel(); //经过输入流通道写给缓冲区数据,就是将通道中的数据 写入缓存块 buffer MappedByteBuffer mbb = sourceCh.map(FileChannel.MapMode.READ_ONLY,0,sourceCh.size()); // ByteBuffer byteBuffer = ByteBuffer.allocate(10); // // byteBuffer.putChar('1'); // //写转化为读 // byteBuffer.flip(); // destCh.write(byteBuffer); //经过输出流通道,获取缓冲区数据,就是将缓冲区中的数据 写入通道 destCh.write(mbb); sourceCh.close(); destCh.close(); } }