Unknown buffer size to read from 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 do not know the size of this stream. How to read this stream and print it?

+6
source share
4 answers

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

But I assume that you put a standard InputStream with a DataInputStream for a good reason: parse binary data. (Note: Scanner used only for text data.)

The JavaDoc for DataInputStream shows you that this class has two different ways to specify EOF: each method returns -1 or throws a EOFException . Rule of thumb:

  • Each method that inherits from InputStream uses the "return -1 " convention,
  • Each method NOT inherited from InputStream throws an 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 at the beginning and find every method that you use from a DataInputStream - the rule may break.

+8
source

Call is.read(byte[]) , skipping the previously allocated buffer (you can continue reusing the same buffer). The function will return the number of bytes actually read or -1 at the end of the stream (in this case it will stop):

 byte[] buf = new byte[8192]; int nread; while ((nread = is.read(buf)) >= 0) { // process the first `nread` bytes of `buf` } 
+2
source
 byte[] buffer = new byte[100]; int numberRead = 0; do{ numberRead = is.read(buffer); if (numberRead != -1){ // do work here } }while (numberRead == buffer.length); 

Continue reading the specified buffer size in the loop. If the return value is less than the size of the buffer, which, as you know, reached the end of the stream. If the return value is -1, there is no data in the buffer.

DataInputStream.read

+1
source

DataInputStream is something obsolete. Instead, I recommend using Scanner .

 Scanner sc = new Scanner (process.getInputStream()); while (sc.hasNextXxx()) { System.out.println(sc.nextXxx()); } 
-1
source

Source: https://habr.com/ru/post/897633/


All Articles