对我而言,在编程中Java中的I/O流是最容易被误解的概念。
假设我们从套接字连接中获取输入流:
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
当我从远程服务器获取数据时,以下哪种描述是正确的?
Data stored in the
in
variable. When extra data comes from server, it appends toin
, increasing its size. And then we can read data fromin
variable that way:byte[] messageByte = new byte[1000]; boolean end = false; String dataString = ""; while(!end) { bytesRead = in.read(messageByte); messageString += new String(messageByte, 0, bytesRead); if (messageString.length == 100) { end = true; } }
in
is only a link to the source of data and doesn't contain data itself. When we callin.read(messageByte)
1000 bytes copy from the socket tobytesRead
?Alternatively, instead of a socket let's say we have stream connected to file on HDD. When we call
in.read(messageByte)
we read 1000 bytes from HDD, yes?
哪种方法是正确的?我倾向于认为是第二种方法,但如果是这样,那么在套接字案例中数据存储在哪里?当我们读取1000个字节时,远程服务器是否在等待,然后再发送额外的数据?还是来自服务器的数据存储在操作系统中的某个缓冲区中?