我正在玩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'好得多(**重新使用**這些效率非常高)。 –