import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * 用NIO流拷贝文件 * @author 万星明 * @version 1.0 * @time */ public class NIOCopy { public static void main(String[] args) throws Exception { //准备须要拷贝的文件与目标文件 File f1 = new File(""); File f2 = new File("h.mp4"); //建立输入流 FileInputStream fis = new FileInputStream(f1); //根据读取流建立读取通道,同时将文件中的内容读入到通道中 FileChannel rChannel = fis.getChannel(); //建立输出流 FileOutputStream fos = new FileOutputStream(f2); //根据输出流建立写入通道,将通道中的内容写入到文件中 FileChannel wChannel = fos.getChannel(); //建立缓冲区 ByteBuffer bBuffer = ByteBuffer.allocate((int)f1.length()); //将输入通道中的内容输入到缓冲区中 rChannel.read(bBuffer); //将缓冲区的指针反转,指向起始位置 bBuffer.flip(); //将缓冲区的内容写入到输出通道 wChannel.write(bBuffer); System.out.println("拷贝成功!"); //关流 fis.close(); fos.close(); } }