[英]Unknown buffer size to be read from a DataInputStream in java
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?
我该如何阅读此流并打印出来?
It is common to all Streams, that the length is not known in advance. 所有Streams都很常见,事先并不知道长度。 Using a standard
InputStream
the usual solution is to simply call read
until -1
is returned. 使用标准的
InputStream
,通常的解决方案是简单地调用read
直到返回-1
。
But I assume, that you have wrapped a standard InputStream
with a DataInputStream
for a good reason: To parse binary data. 但我假设你已经用
DataInputStream
包装了一个标准的InputStream
,原因很简单:解析二进制数据。 (Note: Scanner
is for textual data only.) (注意:
Scanner
仅用于文本数据。)
The JavaDoc for DataInputStream
shows you, that this class has two different ways to indicate EOF - each method either returns -1
or throws an EOFException
. 该JavaDoc中的
DataInputStream
显示了,这个类有两种不同的方式来表示EOF -每一种方法或者返回-1
或抛出EOFException
。 A rule of thumb is: 经验法则是:
InputStream
uses the "return -1
" convention, InputStream
继承的每个方法都使用“return -1
”约定, InputStream
throws the EOFException
. InputStream
抛出EOFException
。 If you use readShort
for example, read until an exception is thrown, if you use "read()", do so until -1
is returned. 例如,如果使用
readShort
,则读取直到抛出异常,如果使用“read()”,则执行此操作直到返回-1
。
Tip: Be very careful in the beginning and lookup each method you use from DataInputStream
- a rule of thumb can break. 提示:在开始时要非常小心,并从
DataInputStream
查找您使用的每个方法 - 经验法则可能会中断。
Call is.read(byte[])
repeadely, passing a pre-allocated buffer (you can keep reusing the same buffer). 重复调用
is.read(byte[])
,传递预先分配的缓冲区(您可以继续重用相同的缓冲区)。 The function will return the number of bytes actually read, or -1 at the end of the stream (in which case, stop): 该函数将返回实际读取的字节数,或者在流的末尾返回-1(在这种情况下,停止):
byte[] buf = new byte[8192];
int nread;
while ((nread = is.read(buf)) >= 0) {
// process the first `nread` bytes of `buf`
}
byte[] buffer = new byte[100];
int numberRead = 0;
do{
numberRead = is.read(buffer);
if (numberRead != -1){
// do work here
}
}while (numberRead == buffer.length);
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.
如果返回值为-1,则缓冲区中没有数据。
DataInputStream
is something obsolete. DataInputStream
已经过时了。 I recommend you to use Scanner
instead. 我建议你改用
Scanner
。
Scanner sc = new Scanner (process.getInputStream());
while (sc.hasNextXxx()) {
System.out.println(sc.nextXxx());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.