Here you can find the source of readBytes(InputStream in, int expectedBytes, long timeoutMs)
Parameter | Description |
---|---|
in | a parameter |
expectedBytes | the total number of bytes to read, a byte array of this size is created |
timeoutMs | a parameter |
Parameter | Description |
---|---|
TimeoutException | an exception |
IOException | an exception |
public static final byte[] readBytes(InputStream in, int expectedBytes, long timeoutMs) throws TimeoutException, IOException, InterruptedException
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeoutException; public class Main { /**//from w ww .j a va2s . c om * Read expectedBytes from an input stream and time out if no change on the input stream for more than timeoutMs.<br/> * Bytes are read from the input stream as they become available. * @param in * @param expectedBytes the total number of bytes to read, a byte array of this size is created * @param timeoutMs * @throws TimeoutException * @throws IOException * @return */ public static final byte[] readBytes(InputStream in, int expectedBytes, long timeoutMs) throws TimeoutException, IOException, InterruptedException { byte[] bytes = new byte[expectedBytes]; int pos = 0; long lastTimeAvailable = System.currentTimeMillis(); do { int avail = in.available(); if (avail > 0) { //have an new data, read the available bytes and add to the byte array, note we use expectedBytes-pos, to calculate the remaining bytes //required to read int btsRead = in.read(bytes, pos, Math.min(avail, expectedBytes - pos)); pos += btsRead; if (pos >= expectedBytes) //we've read all required bytes, exit the loop break; //save the last time data was available lastTimeAvailable = System.currentTimeMillis(); } else if ((System.currentTimeMillis() - lastTimeAvailable) > timeoutMs) { //check for timeout throw new TimeoutException( "Timeout while reading data from the input stream: got only " + pos + " bytes of " + expectedBytes + " last seen " + lastTimeAvailable + " diff " + (System.currentTimeMillis() - lastTimeAvailable)); } else { //sleep to simulate IO blocking and avoid consuming CPU resources on IO wait Thread.sleep(100); } } while (true); return bytes; } }