我在閱讀我的文件時遇到問題。我對NIO也很新穎。我想發送到服務器的文件的實際大小几乎是900MB,並且只收到3MB。不完整的文件複製Java NIO
服務器的讀取端代碼:
private void read(SelectionKey key) throws IOException{
SocketChannel socket = (SocketChannel)key.channel();
RandomAccessFile aFile = null;
ByteBuffer buffer = ByteBuffer.allocate(300000000);
try{
aFile = new RandomAccessFile("D:/test2/test.rar","rw");
FileChannel inChannel = aFile.getChannel();
while(socket.read(buffer) > 0){
buffer.flip();
inChannel.write(buffer);
buffer.compact();
}
System.out.println("End of file reached..");
}catch(Exception e){
e.printStackTrace();
}
}
這是我的代碼爲客戶端的write方法:
private void write(SelectionKey key) throws IOException {
SocketChannel socket = (SocketChannel) key.channel();
RandomAccessFile aFile = null;
try {
File f = new File("D:/test.rar");
aFile = new RandomAccessFile(f, "r");
ByteBuffer buffer = ByteBuffer.allocate(300000000);
FileChannel inChannel = aFile.getChannel();
while (inChannel.read(buffer) > 0) {
buffer.flip();
socket.write(buffer);
buffer.compact();
}
aFile.close();
inChannel.close();
key.interestOps(SelectionKey.OP_READ);
} catch (Exception e) {
e.printStackTrace();
}
}
只是想:read()通常會告訴您已經讀取的確切數字字節。這並不意味着讀取了所有的緩衝區字節。至少在老派的IO中,你必須循環,直到你讀取緩衝區中的所有字節。 – GhostCat
'socket.read(buffer)> 0' +非阻塞IO =失敗,因爲零並不意味着數據流的結束,只有當前沒有數據準備好被讀取。所以你正在以完全封鎖的方式閱讀,而處理NIO,這顯然不起作用。 – user3707125