Java NIO에서 채널 중 하나가 FileChannel이라면, 하나의 채널로부터 또다른 채널에 데이터를 직접 전송할 수 있다. FileChannel 클래스는 개발자를 위한 transferTo()와 transferFrom() 메소드를 갖고 있다.

transferFrom()


FileChannel.transferFrom() 메소드는 소스 채널로부터 FileChannel에 데이터를 전송한다. 다음 간단한 예제가 있다:

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel      fromChannel = fromFile.getChannel();

RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel      toChannel = toFile.getChannel();

long position = 0;
long count    = fromChannel.size();

toChannel.transferFrom(fromChannel, position, count);

기록을 시작하는 대상 파일의 위치를 말해주는 (position)과, 최대 얼마나 많은 bytes를 전송할 수 있는지를 말해주는 (count) 매개변수가 있다. 만약 소스 채널이 count bytes 보다 작다면, 전송이 덜 된 것이다.


추가적으로, 일부 SocketChannel의 구현들은 SocketChannel이 현재 내부 버퍼가 준비되어 있어야만 데이터를 전송할 수 있다 - SocketChannel이 나중에 더 많은 데이터를 사용할 지라도 말이다. 그러므로, 이는 SocketChannel에서 FileChannelcount만큼 요청된 데이터가 전부 전송되지 않을 수도 있다는 것이다.

transferTo()


transferTo() 메소드는 FileChannel로부터 일부 다른 채널에 전송한다. 다음 간단한 예제가 있다:

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel      fromChannel = fromFile.getChannel();

RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel      toChannel = toFile.getChannel();

long position = 0;
long count    = fromChannel.size();

fromChannel.transferTo(position, count, toChannel);

이전 예제와 어떻게 비슷한지 주목하기 바란다. 유일하게 차이점은 FileChannel 객체 메소드 호출되는 곳이다. 나머지는 동일하다.


SocketChannel의 이슈는 transferTo() 메소드에서도 나타난다. SocketChannel 구현은 FileChannel의 전송 버퍼가 꽉 찰 때까지 bytes를 전송하고, 그 후에 중지 할 수도 있다.



<원문 출처>


'Programming > Java NIO' 카테고리의 다른 글

FileChannel  (0) 2015.09.09
Selector  (0) 2015.09.09
Scatter / Gather  (0) 2015.09.08
Buffer  (0) 2015.09.08
Channel  (0) 2015.09.08
Posted by 레미파
,