FileChannel을 이용한 파일 복사
JDK1.4에 추가된 FileChannel 클래스는
파일 입출력을 위한 채널로 AbstractInterruptibleChannel 클래스를 상속해서 비동기적으로 중단될 수 있게 되어있으며
ByteChannel 인터페이스를 구현해서 읽기와 쓰기를 동시에 할 수 있는 장점이 있습니다.
이 Channel이라는 것은 네트웍
또는 파일 뿐 아니라 데이터의 입출력을 할 때에도 사용되는 통로이며 FileStream을 이용하여 스트림을 만들면 이 스트림으로부터
getChannel() 메소드를 통해 FileChanne을 얻어 올 수 있습니다.
또한 FileChannel 클래스는 new를
통해 인스턴스를 만들 수 없는데 왜냐하면 FileChannel 클래스는 추상 클래스이며 어떠한 클래스 method도 가지고 있지 않기 때문
입니다. FileInputStream, FileOutputStream, RandomAccessFile 클래스의 getChannel() 메소드를
호출함으로서 FileChannel 클래스의 인스턴스를 얻을 수 있는데 FileInputStream의 getChannel()메소드를 사용한다면
읽기만 할 수 있는 FileChannel을 얻게 되고, FileOutputStream의 getChannel() 메소드를 사용한다면 쓰기만 할 수
있는 FileChannel을 얻게 되고, RandomAccessFile의 getChannel() 메소드를 사용한다면 읽기와 쓰기를 동시에 할 수
있는 FileChannel을 얻을 수 있습니다.
아래 예를 참고 하세요~
[FileChannelTest.java] import java.io.FileInputStream;
import java.io.FileOutputStream; import java.nio.channels.FileChannel;
public class FileChannelTest {
/** * @param
args */ public static void main(String[] args) throws
Exception{ // TODO Auto-generated method stub
long fsize = 0;
//원본 파일 FileInputStream fis = new
FileInputStream("c:\\application.log"); //복사될 곳
FileOutputStream fos = new
FileOutputStream("d:\\application.log");
//FileStream에서 FileChannel을 가져옴 FileChannel fcin =
fis.getChannel(); FileChannel fcout = fos.getChannel();
//복사될 파일의 size fsize
= fcin.size(); //transferTo 메소드를 이용하여
복사할 파일의 채널을 지정 //복사할 position은 0부터 파일 크기 만큼
fcin.transferTo(0, fsize, fcout);
fcout.close(); fcin.close();
fos.close(); fis.close();
System.out.println("Copy OK~"); }
}
|
댓글 없음:
댓글 쓰기