[Java] 阻塞与非阻塞IO

博客首页 » Java 阻塞与非阻塞IO

发布于 11 Dec 2015 02:21
标签 blog
Java阻塞IO与非阻塞NIO
http://www.open-open.com/lib/view/open1420790598093.html

From a Blog on IBM
https://www.ibm.com/developerworks/community/blogs/pmuellr/entry/java_process_management_arghhs?lang=en

    Process process = Runtime.getRuntime().exec(new String[] {"sleep", "10"});
    java.io.InputStream iStream = process.getInputStream();
    java.nio.channels.ReadableByteChannel channel =
        java.nio.channels.Channels.newChannel(iStream);
    System.out.println(channel.getClass().getName());
    System.out.println(channel instanceof java.nio.channels.SelectableChannel);
 
//and the result is ...
 
    java.nio.channels.Channels$ReadableByteChannelImpl    false

From StackOverflow
http://stackoverflow.com/questions/1033653/is-it-possible-to-read-the-process-stdout-inputstream-into-an-nio-bytebuffer

Believe it or not, I think the writable byte channel you want is

ByteArrayOutputStream ostream = new ByteArrayOutputStream(<some large number>);
WritableByteChannel destination = Channels.newChannel(ostream);

Then when done

ostream.toByteArray()

contains the bytes to process. Or, if you want a byte buffer,
ByteBuffer.wrap(ostream.toByteArray())

I don't see here how you get the output outside the runnable, but I suspect your original code had that. Otherwise you might want the StreamConsumer to be a Callable<ByteBuffer>.

本页面的文字允许在知识共享 署名-相同方式共享 3.0协议和GNU自由文档许可证下修改和再使用,仅有一个特殊要求,请用链接方式注明文章引用出处及作者。请协助维护作者合法权益。


系列文章

文章列表

  • Java 阻塞与非阻塞IO

这篇文章对你有帮助吗,投个票吧?

rating: 0+x

留下你的评论

Add a New Comment