Search in sources :

Example 11 with AsynchronousFileChannel

use of java.nio.channels.AsynchronousFileChannel in project Gargoyle by callakrsos.

the class FileUtil method asynchRead.

public static <T> void asynchRead(Path path, Function<byte[], T> handler) throws IOException {
    AsynchronousFileChannel open = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
    // ByteBuffer 크기를 8k로 축소
    ByteBuffer byteBuffer = ByteBuffer.allocate(8 * 1024);
    long position = 0L;
    Long attachment = 0L;
    long fileSize = open.size();
    open.read(byteBuffer, position, attachment, new CompletionHandler<Integer, Long>() {

        @Override
        public void completed(Integer result, Long attachment) {
            if (result == -1)
                close();
            // 읽기 쓰기 병행시 flip을 호출해줘야함.
            byteBuffer.flip();
            byteBuffer.mark();
            handler.apply(byteBuffer.array());
            byteBuffer.reset();
            // 버퍼 사이즈보다 작다면 파일의 끝까지 읽은 것이므로 종료 처리
            if (result == fileSize || result < byteBuffer.capacity()) {
                //// asyncFileChannel 닫기
                close();
                return;
            }
            // 읽을 내용이 남아있으므로 반복 회수를 증가 시키고 다시 읽는다.
            attachment++;
            open.read(byteBuffer, result * attachment, attachment, this);
        }

        @Override
        public void failed(Throwable exc, Long attachment) {
            exc.printStackTrace();
            close();
        }

        public void close() {
            try {
                if (open != null)
                    open.close();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    });
}
Also used : AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Aggregations

AsynchronousFileChannel (java.nio.channels.AsynchronousFileChannel)11 IOException (java.io.IOException)7 Path (java.nio.file.Path)4 File (java.io.File)3 Test (org.junit.Test)3 URI (java.net.URI)2 ByteBuffer (java.nio.ByteBuffer)2 ReadableByteChannel (java.nio.channels.ReadableByteChannel)2 ExecutorService (java.util.concurrent.ExecutorService)2 Suspendable (co.paralleluniverse.fibers.Suspendable)1 Http2Response (com.webpieces.hpack.api.dto.Http2Response)1 StreamWriter (com.webpieces.http2engine.api.StreamWriter)1 DataFrame (com.webpieces.http2parser.api.dto.DataFrame)1 StatusCode (com.webpieces.http2parser.api.dto.StatusCode)1 Http2Header (com.webpieces.http2parser.api.dto.lib.Http2Header)1 Http2HeaderName (com.webpieces.http2parser.api.dto.lib.Http2HeaderName)1 OutputStream (java.io.OutputStream)1 ClosedChannelException (java.nio.channels.ClosedChannelException)1 CompletionHandler (java.nio.channels.CompletionHandler)1 FileChannel (java.nio.channels.FileChannel)1