2014-11-10 2 views
1

파일 복사를 구현하기 위해 AsynchronousFileChannel을 사용하려고합니다.Java AsynchronousFileChannel 및 ByteBuffer

AsynchronousFileChannel asyncRead = AsynchronousFileChannel.open(sourcePath); 
AsynchronousFileChannel asyncWrite = AsynchronousFileChannel.open(targetPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE); 

읽기에 대한 CompletionHandler 그런 다음

CompletionHandler<Integer, ByteBuffer> handlerRead = new CompletionHandler<Integer, ByteBuffer>() { 

     @Override 
     public void completed(Integer arg0, ByteBuffer arg1) { 
      System.out.println("finished read ..."); 

      // question line 
      asyncWrite.write(ByteBuffer.wrap(arg1.array()), 0, null, handlerWrite); 
     } 

     @Override 
     public void failed(Throwable arg0, ByteBuffer arg1) { 
      System.out.println("failed to read ..."); 
     } 
    }; 

처럼 보이는 읽기 및 쓰기에 대한 AsynchronousFileChannel 객체 내가 읽은 후

asyncRead.read(buffer, 0, buffer, handlerRead); 

질문은 읽을 파일을 시작 선언된다 완료되면, 내가 파일을 쓰는 경우 (어디서 전화인지 확인하려면 "질문 라인"주석을 참조하십시오)

// no output 
asyncWrite.write(arg1, 0, null, handlerWrite); 

기록한 내용이 없습니다. 나는 내용이 써보기 위해 다시

// works fine 
asyncWrite.write(ByteBuffer.wrap(arg1.array()), 0, null, handlerWrite); 

버퍼를 포장해야

내 질문에, 나는 또 다른의 ByteBuffer의 내용을 포장하는의 ByteBuffer를 사용해야하는 이유는 무엇입니까?

답변

3

다른 ByteBuffer의 내용을 감싸기 위해 ByteBuffer를 사용해야하는 이유는 무엇입니까?

그렇지 않습니다. 대신 원래 ByteBuffer을 뒤집어 놓았어야합니다. wrap()을 호출하여 비슷한 효과를 얻었는데, 새로 포장 된 ByteBufferposition을 0으로 설정합니다.

+0

'asyncWrite.write ((ByteBuffer) arg1.flip(), 0, null, handlerWrite);'시도했는데 작동합니다. 힌트를 주셔서 감사합니다.하지만 아직 어떤 일이 발생했는지 아직 알 수는 없습니다. –

+1

그래서 플립()에 대한 Javadoc을보십시오. 이것의 목적은 Buffer를 쓰기 가능한 상태로 만드는 것입니다. 일반적으로 그들은 읽기 쉬운 상태에 있습니다. 나중에 다시 읽으려면'compact()'또는'clear()'를해야합니다. – EJP

+0

그래, 나는 이미 의사를 읽었지만 아직 그것을 소화하지는 않았다. 당신이 말했던 것에서, 포인터를 포인터로 옮기려면 두 번째 시간 동안리스트를 반복하고 싶다면 반복자처럼 들립니다. 내 이해가 맞습니까? –