Created
April 27, 2012 07:22
-
-
Save nschlimm/2506857 to your computer and use it in GitHub Desktop.
Revisions
-
nschlimm created this gist
Apr 27, 2012 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,54 @@ public class ReadWriteAll { public static void main(String[] args) throws InterruptedException, IOException { try (AsynchronousFileChannel outputfile = AsynchronousFileChannel.open(Paths.get("E:/temp/afile.out"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE)) { writeFully(outputfile, (ByteBuffer) ByteBuffer.allocateDirect(1048576).put(new byte[1048576]).flip(), 0L); readAll(outputfile, (ByteBuffer) ByteBuffer.allocateDirect(1000).put(new byte[1000]).flip(), 1000L); } catch (Exception e) { e.printStackTrace(); } } static void readAll(final AsynchronousFileChannel ch, final ByteBuffer dst, long filePosition) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); ch.read(dst, filePosition, filePosition, new CompletionHandler<Integer, Long>() { public void completed(Integer bytesTransferred, Long filePosition) { if (bytesTransferred > 0) { long p = filePosition + bytesTransferred; ch.read(dst, p, p, this); } else { latch.countDown(); } } public void failed(Throwable exc, Long position) { } }); latch.await(); } static void writeFully(final AsynchronousFileChannel ch, final ByteBuffer src, long filePosition) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); ch.write(src, filePosition, filePosition, new CompletionHandler<Integer, Long>() { public void completed(Integer bytesTransferred, Long filePosition) { if (src.hasRemaining()) { long newFilePosition = filePosition + bytesTransferred; ch.write(src, newFilePosition, newFilePosition, this); } else { latch.countDown(); } } public void failed(Throwable exc, Long position) { } }); latch.await(); } }