java DataInputStream.read() 与 DataInputStream.readFully()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25897627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:54:42  来源:igfitidea点击:

DataInputStream.read() vs DataInputStream.readFully()

javasocketsjava-io

提问by Krimson

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()因此我可以假设它是一回事吗?

回答by Lolo

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

声明的 Javadoc DataInput.readFully(byte[] b)

Reads some bytes from an input stream and stores them into the buffer array b. The number of bytes read is equal to the length of b.

从输入流中读取一些字节并将它们存储到缓冲区数组中b读取的字节数等于 的长度b

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

声明的 Javadoc DataInputStream.read(byte[] b)

Reads some number of bytes from the contained input stream and stores them into the buffer array 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.

从包含的输入流中读取一定数量的字节并将它们存储到缓冲区数组中b实际读取的字节数作为整数返回。此方法会阻塞,直到输入数据可用、检测到文件结尾或抛出异常

Basically, readFully()will read exactlyb.lengthbytes, whereas read()will read up tob.length, maybe less, whatever is available from the input stream.

基本上,readFully()准确读取b.length字节,而read()将读取最多b.length或更少的输入流中可用的任何内容。

回答by Lluis Felisart

Using readyou 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 readFullya 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,不需要检查返回值,简化一点。