NIO系列:3.Channe拷贝文件示例

使用 FileChannel(通道) 和方法 transferFrom,完成文件的拷贝:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
 
public class NIOFileChannel04 {
    public static void main(String[] args)  throws Exception {
 
        //创建相关流
        FileInputStream fileInputStream = new FileInputStream("d:\\a.jpg");
        FileOutputStream fileOutputStream = new FileOutputStream("d:\\a2.jpg");
 
        //获取各个流对应的filechannel
        FileChannel sourceCh = fileInputStream.getChannel();
        FileChannel destCh = fileOutputStream.getChannel();
 
        //使用transferForm完成拷贝
        destCh.transferFrom(sourceCh,0,sourceCh.size());
        //关闭相关通道和流
        sourceCh.close();
        destCh.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章