Is there a non-blocking file read API in java? If not would it be wise to build one in C++ and call it from a开发者_StackOverflow社区 java app via JNI?
My original answer is now wrong, since the addition of AsynchronousFileChannel
in Java 7.
You still cannot select on a file, but there are now two asynchronous file read methods: one that takes a callback and another that returns a Future
.
It may be cleaner to use the callback method (and dispatch an event from the callback) than to have a dedicated thread polling a pipe.
No, FileChannel
does not extend SelectableChannel
.
Probably because not all OSes support it.
Windows does, and in theory you could write a windows-specific C++ library and call it via JNI, but it is a lot of work to integrate this with java.nio
.
I would rather have a worker thread copy the file contents to a pipe and do non-blocking reads on the other end of the pipe.
AsynchronousFileChannel
is the right answer. Yet, it does not provide an easy API. It is quite verbose to use it comparing with the similar usage of java.nio.file.Files
that provides simple static methods, such as: readAllLines
or lines
. Unfortunately Files
methods are synchronous.
The AsyncFiles
alternative from RxIo provides the corresponding non-blocking methods, with 3 different APIs: callback based, CompletableFuture
and also with reactive streams. Here it is an example with reactive streams:
AsyncFiles
.lines(path)
.subscribe(doOnNext(line -> /*... use line from background thread ...*/));
精彩评论