JavaSE:NIO

使用FileChannel完成文件的复制

1. 图解

2. 代码

 1 import  java.io.FileInputStream;
 3 import  java.io.FileNotFoundException;
 5 import  java.io.FileOutputStream;
 6 
 7 import  java.io.IOException;
 8 
 9 import  java.nio.ByteBuffer;
10 
11 import  java.nio.channels.FileChannel;
12 
13 
14 
15 public class Channel完成文件复制 {
16 
17   main() {
    
    // 创建输入流和输出流 (依赖于IO流获取channel)
21     // 输入流 22     FileInputStream fileInputStream = new FileInputStream("C:\Users\sunzh\Desktop\wxy.png"); 23     // 输出流 24     FileOutputStream fileOutputStream = new FileOutputStream("C:\Users\sunzh\Desktop\lagou_myself\nio\复制.png"); 25      26   // 通过IO流, 获取channel通道
27     FileChannel f1 = fis.getChannel(); 28     FileChannel f2 = fos.getChannel(); 29 30 31     // 创建缓冲区 32     ByteBuffer buffer = ByteBuffer.allocate(1024); 33      34     // 循环
      // 利用通道f1, 将内容读入到buffer中
35     while(f1.read(buffer) != -1) { 36 37       // 切换模式, 改变position和limit的位置 (limit = 原position, position = 0) 38       buffer.flip();
39       // 输出到f2中 41       f2.write(buffer); 42 43       // 还原所有指针(变量 position, limit ... )的位置 45       buffer.clear();   46 47     } 48     // 关流 50     fos.close(); 51     fis.close(); 54 }
原文地址:https://www.cnblogs.com/JasperZhao/p/14958942.html