Asynchronous File IO in JavaAsynchronous File I/O in JavaAsynchronous File I/O in Java is a framework I created because I got tired of waiting for JSR 203 The source code for the project can be found in my subversion sandbox as part of the Apache Mina project https://svn.apache.org/repos/asf/mina/sandbox/mheath/aioj To build the project use Maven 2 and run "mvn package". This will produce two artifacts. A Java .jar file containing the Java classes and libaioj.so which contains the the native binaries that make the POSIX AIO calls to do asynchronous file IO in Java. ExampleBelow is a simple example of how to use Asynchronous File I/O in Java. AIOTest.java import java.io.FileInputStream; import java.nio.ByteBuffer; import org.apache.aio.AioFutureListener; import org.apache.aio.AioFutureReadWrite; import org.apache.aio.AsynchronousFileChannel; public class AIOTest { public static void main(String[] args) throws Exception { FileInputStream in = new FileInputStream("/etc/passwd"); AsynchronousFileChannel achannel = new AsynchronousFileChannel(in.getFD()); AioFutureListener<AioFutureReadWrite> listener = new AioFutureListener<AioFutureReadWrite>() { public void onCompletion(AioFutureReadWrite ioFuture) { System.out.println("In callback"); byte[] data = new byte[ioFuture.getBuffer().limit() - ioFuture.getBuffer().position()]; ioFuture.getBuffer().get(data); System.out.println(" Buffer contains: " + new String(data)); } }; ByteBuffer buffer = ByteBuffer.allocateDirect(4096); AioFutureReadWrite future = achannel.read(buffer, 0); future.addListener(listener); future.join(); } }
|