01.JAVA/Java2009. 6. 29. 17:12
반응형

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;


public class FChannel {

 public FChannel() {
  // TODO Auto-generated constructor stub
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  long size = 0;
 
  try {
   // 원본 파일
   FileInputStream fis = new FileInputStream("D:\\filedown2\\pn2060.exe");
   
   // 카피할 파일
   FileOutputStream fos = new FileOutputStream("D:\\filedown2\\pn2060_copy.exe");
   
   
   // FileStream 으로부터 File Channel 을 가져온다.
   FileChannel fcin = fis.getChannel();
   FileChannel fcout = fos.getChannel();
   
   size = fcin.size();
   
   System.out.println("In File Size :" + size);
   
   // 파일의 처음 부터 끝까지, fcout 으로 전송 copy
   fcin.transferTo(0, size, fcout);
   
   fcout.close();
   fcin.close();
   
   fos.close();
   fis.close();
   
   System.out.println("File Copy OK");
   
   
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }
 }

}

[출처] FileChannel을 이용한 파일 복사 팁|작성자 리트머스


=================

import java.io.*;
import java.nio.channels.*;

public static void copyFile(String source, String target) throws IOException {
    FileChannel inChannel = new FileInputStream(source).getChannel();
    FileChannel outChannel = new FileOutputStream(target).getChannel();
    try {
        // magic number for Windows, 64Mb - 32Kb
        int maxCount = (64 * 1024 * 1024) - (32 * 1024);
        long size = inChannel.size();
        long position = 0;
        while (position < size) {
            position += inChannel.transferTo(position, maxCount, outChannel);
        }
    } catch (IOException e) {
        throw e;
    } finally {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}
Posted by 1010