简体   繁体   English

DataInputStream.read() 与 DataInputStream.readFully()

[英]DataInputStream.read() vs DataInputStream.readFully()

Im making a simple TCP/IP Socket app我正在制作一个简单的 TCP/IP Socket 应用程序

Whats the different between doing this:这样做有什么不同:

DataInputStream in = new DataInputStream(clientSocket.getInputStream());

byte[] buffer = new byte[100];
in.readFully(buffer);

versus doing this:与这样做:

DataInputStream in = new DataInputStream(clientSocket.getInputStream());

byte[] buffer = new byte[100];
in.read(buffer);

I had a look at the documentation, they have the same exact description.我查看了文档,它们具有相同的确切描述。 readFully() and read() So can I assume its the same thing? readFully()read()那么我可以假设它是一样的吗?

The Javadoc for DataInput.readFully(byte[] b) states: DataInput.readFully(byte[] b)的 Javadoc 指出:

Reads some bytes from an input stream and stores them into the buffer array b .从输入流中读取一些字节并将它们存储到缓冲区数组b The number of bytes read is equal to the length of b .读取的字节数等于b的长度

The Javadoc for DataInputStream.read(byte[] b) states: DataInputStream.read(byte[] b)的 Javadoc 指出:

Reads some number of bytes from the contained input stream and stores them into the buffer array b .从包含的输入流中读取一定数量的字节并将它们存储到缓冲区数组b The number of bytes actually read is returned as an integer.实际读取的字节数作为整数返回。 This method blocks until input data is available, end of file is detected, or an exception is thrown .此方法会阻塞,直到输入数据可用、检测到文件结尾或抛出异常

Basically, readFully() will read exactly b.length bytes, whereas read() will read up to b.length , maybe less, whatever is available from the input stream.基本上, readFully()准确读取b.length字节,而read()将读取最多b.length ,可能更少,无论输入流中可用什么。

Using read you need to check return value to know how many bytes have been really read使用read您需要检查返回值以了解实际读取了多少字节

byte[] buffer = new byte[100];
if (in.read(buffer) < 100){
   // fail
   }

instead with readFully a IOException will be thrown if the 100 bytes could not be read, don't need to check return value, simplify a bit.readFully代替,如果 100 个字节不能被读取,就会抛出一个 IOException ,不需要检查返回值,简化一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM