【发布时间】:2016-08-21 15:52:08
【问题描述】:
我在读取文件时遇到问题。我对 NIO 也很陌生。我要发送到服务器的文件的实际大小几乎是 900MB 并且只收到了 3MB。
服务器端读取代码:
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();
}
}
这是我的客户端写方法的代码:
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 中,您必须循环直到从缓冲区中读取所有字节。
-
socket.read(buffer) > 0+ non-blocking IO = failure,因为零并不意味着流的结束,只是没有准备好读取的数据。因此,您在处理 NIO 时以完全阻塞的方式阅读,这显然行不通。
标签: java asynchronous nio filechannel