본문 바로가기

Java/[Basic Source]

FileChannel을 이용한 파일 copy

FileChannel을 이용하여 파일을 복사하게 되면,

일반적으로 사용하는 InputStream을 이용해서 loop를 돌면서 특정 buffer size만큼 읽어서

파일에 write하는 방식보다 좋은 성능을 낼수 있네요...


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:\\xxxx\\xxx.zip");


   // 카피할 파일
   FileOutputStream fos = new FileOutputStream(
     "D:\\xxxx\\xxx_copy.zip");


   // 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();
  }
 }


 }