从 java 中的 DataInputStream 读取的未知缓冲区大小
我有以下语句:
DataInputStream is = new DataInputStream(process.getInputStream());
我想打印此输入流的内容,但我不知道此流的大小。我应该如何读取该流并打印它?
I have the following statement:
DataInputStream is = new DataInputStream(process.getInputStream());
I would like to print the contents of this input stream but I dont know the size of this stream. How should I read this stream and print it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于所有流来说,都有一个共同点:长度是事先未知的。使用标准
InputStream
,通常的解决方案是简单地调用read
,直到返回-1
。但我认为,您使用
DataInputStream
包装标准InputStream
是有充分理由的:解析二进制数据。 (注意:Scanner
仅适用于文本数据。)JavaDoc for
DataInputStream
向您展示,此类有两种不同的方式来指示 EOF - 每种方法要么返回-1
要么抛出EOFException
。经验法则是:InputStream
继承的每个方法都使用“return-1
”约定,继承的每个方法NOT >InputStream
抛出EOFException
。例如,如果您使用
readShort
,则读取直到抛出异常;如果您使用“read()”,则一直读取直到返回-1
。提示:一开始要非常小心,并从
DataInputStream
中查找您使用的每个方法 - 经验法则可能会被打破。It is common to all Streams, that the length is not known in advance. Using a standard
InputStream
the usual solution is to simply callread
until-1
is returned.But I assume, that you have wrapped a standard
InputStream
with aDataInputStream
for a good reason: To parse binary data. (Note:Scanner
is for textual data only.)The JavaDoc for
DataInputStream
shows you, that this class has two different ways to indicate EOF - each method either returns-1
or throws anEOFException
. A rule of thumb is:InputStream
uses the "return-1
" convention,InputStream
throws theEOFException
.If you use
readShort
for example, read until an exception is thrown, if you use "read()", do so until-1
is returned.Tip: Be very careful in the beginning and lookup each method you use from
DataInputStream
- a rule of thumb can break.调用 重复
is.read(byte[])
,传递预先分配的缓冲区(您可以继续重用相同的缓冲区)。该函数将返回实际读取的字节数,或在流末尾返回 -1(在这种情况下,停止):Call
is.read(byte[])
repeadely, passing a pre-allocated buffer (you can keep reusing the same buffer). The function will return the number of bytes actually read, or -1 at the end of the stream (in which case, stop):继续循环读取设定的缓冲区大小。如果返回值小于缓冲区的大小,您就知道已经到达流的末尾。如果返回值为-1,则缓冲区中没有数据。
DataInputStream.read
Keep reading a set buffer size in a loop. If the return value is ever less than the size of the buffer you know you have reached the end of the stream. If the return value is -1, there is no data in the buffer.
DataInputStream.read
DataInputStream
已经过时了。我建议您改用Scanner
。DataInputStream
is something obsolete. I recommend you to useScanner
instead.