我正在尝试使用NIO库。我想监听8888端口的连接,一旦接受到一个连接,就将该通道中的所有内容转储到somefile
。
我知道如何使用ByteBuffers
实现,但我想尝试使用传闻中效率超高的FileChannel.transferFrom
来实现。
这是我的代码:
ServerSocketChannel ssChannel = ServerSocketChannel.open();
ssChannel.socket().bind(new InetSocketAddress(8888));
SocketChannel sChannel = ssChannel.accept();
FileChannel out = new FileOutputStream("somefile").getChannel();
while (... sChannel has not reached the end of the stream ...) <-- what to put here?
out.transferFrom(sChannel, out.position(), BUF_SIZE);
out.close();
那么,我的问题是:如何表达“transferFrom
直到到达流的末尾”?
编辑:将1024更改为BUF_SIZE,因为所使用的缓冲区的大小与问题无关。
transfer
方法的内部情况。 - bestsss