6

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?

Joan Venge
  • 315,713
  • 212
  • 479
  • 689
nikhil
  • 9,023
  • 22
  • 55
  • 81

4 Answers4

8

It is common to all Streams, that the length is not known in advance. Using a standard InputStream the usual solution is to simply call read until -1 is returned.

But I assume, that you have wrapped a standard InputStream with a DataInputStream 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 an EOFException. A rule of thumb is:

  • Every method which is inherited from InputStream uses the "return -1" convention,
  • Every method NOT inherited from InputStream throws the EOFException.

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.

A.H.
  • 63,967
  • 15
  • 92
  • 126
  • +1 The [tutorial](http://download.oracle.com/javase/tutorial/essential/io/datastreams.html) elaborates, "Notice that `DataStreams` detects an end-of-file condition by catching `EOFException`, instead of testing for an invalid return value." – trashgod Sep 19 '11 at 20:37
  • I thought, I made the distinction between DIS and IS clear. But I edited the answer according to your input. TNX – A.H. Sep 19 '11 at 20:55
  • Aha, methods implementing `DataInput`, which are _not_ inherited from `InputStream`, throw `EOFException`. Thanks for clarifying. – trashgod Sep 19 '11 at 21:18
2

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):

byte[] buf = new byte[8192];
int nread;
while ((nread = is.read(buf)) >= 0) {
  // process the first `nread` bytes of `buf`
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1
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.

DataInputStream.read

John B
  • 32,493
  • 6
  • 77
  • 98
-1

DataInputStream is something obsolete. I recommend you to use Scanner instead.

Scanner sc = new Scanner (process.getInputStream());
while (sc.hasNextXxx()) {
   System.out.println(sc.nextXxx());
}
Roman
  • 64,384
  • 92
  • 238
  • 332