要从java中的DataInputStream读取的未知缓冲区大小
我有以下声明:
DataInputStream is = new DataInputStream(process.getInputStream());
我想打印此输入流的内容,但我不知道此流的大小。 我该如何阅读此流并打印出来?
所有Streams都很常见,事先并不知道长度。 使用标准的InputStream
,通常的解决方案是简单地调用read
直到返回-1
。
但我认为,你已经用DataInputStream
包装了一个标准的InputStream
,原因很简单:解析二进制数据。 (注意: Scanner
仅用于文本数据。)
DataDputStream的JavaDoc向您显示,此类有两种不同的方式来指示EOF – 每个方法返回-1
或抛出EOFException
。 经验法则是:
- 从
InputStream
inheritance的每个方法都使用“return-1
”约定, - 从
InputStream
inheritance的每个方法都会抛出EOFException
。
例如,如果使用readShort
,则读取直到抛出exception,如果使用“read()”,则执行此操作直到返回-1
。
提示:在开始时要非常小心,并从DataInputStream
查找您使用的每个方法 – 经验法则可能会中断。
重复调用is.read(byte[])
,传递预先分配的缓冲区(您可以继续重用相同的缓冲区)。 该函数将返回实际读取的字节数,或者在流的末尾返回-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);
继续在循环中读取设置的缓冲区大小。 如果返回值小于缓冲区的大小,则表示已到达流的末尾。 如果返回值为-1,则缓冲区中没有数据。
DataInputStream.read
DataInputStream
已经过时了。 我建议你改用Scanner
。
Scanner sc = new Scanner (process.getInputStream()); while (sc.hasNextXxx()) { System.out.println(sc.nextXxx()); }