我正在玩NIO库。我试图在端口8888上监听连接,一旦连接被接受,将该通道中的所有内容转储到somefile
。Java NIO:transferFrom直到流结束
我知道如何使用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,由于所使用的缓冲器的大小,是不相干的问题。
你打我吧。但是,您可以使用“Long.MAX_VALUE”而不是“Integer.MAX_VALUE”。 –
没错,但是如果我在第一次调用transferFrom时只得到10个字节中的3个字节呢? – aioobe
也许测试你的源频道:它有一个['int read(ByteBuffer)'](http://download.oracle.com/javase/6/docs/api/java/nio/channels/ReadableByteChannel.html#read% 28java.nio.ByteBuffer%29)方法。如果返回'-1',那么它没有任何内容,因此您将所有内容都传输到'FileChannel'中。如果你想要更健壮的东西,那么你比'ByteBuffer'好得多(**重新使用**这些效率非常高)。 –