How to Get Bytes From a Java Input Stream
In Java, an InputStream object represents a source of a stream of bytes. Those bytes may come from a file, a network connection, a pipe or other possible sources. The common theme is that, although the program might request that a given number of bytes be read, the stream may return fewer bytes -- and therefore require multiple reads to deliver the complete message. You can read any number of bytes from an InputStream in your Java code, as long as you handle this condition correctly.
Instructions
-
-
1
Include the following line at the start of your Java code:
import java.io.*;
-
2
Declare the following variables in preparation for reading from the stream:
int currOffset=0;
int lastRead=0;
-
-
3
Read from the InputStream using a loop until all needed bytes have been read, as in the following sample code:
while (currOffset < numBytes
&& (lastRead=stream.read(buffer,currOffset,numBytes-currOffset))>=0) {
currOffset += lastRead;
}
Replace "buffer" with the location where you want to store the incoming bytes from the InputStream, and "numBytes" with the total number of bytes you need to read.
-
1