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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章