Hi All,
I've tried a number of different ways to read an inputstream and cannot get the -1 for the end of file to trip. Stepped through the code and got to the final carriage return in the stream, but when the next read() is performed, the code goes into neverland. Does not produce an error and seems like it is looping, but I know it isn't (set a breakpoint property and paused it every now and then and the loop counter does not increment). Code is below, any help/suggestions anyone can provide would be greatly appreciated. Thanks
I've tried a number of different ways to read an inputstream and cannot get the -1 for the end of file to trip. Stepped through the code and got to the final carriage return in the stream, but when the next read() is performed, the code goes into neverland. Does not produce an error and seems like it is looping, but I know it isn't (set a breakpoint property and paused it every now and then and the loop counter does not increment). Code is below, any help/suggestions anyone can provide would be greatly appreciated. Thanks
Code:
private byte[] receiveACK(InputStream in, PrintStream p, int portNumber) throws Exception {
int nextByte = 0;
int loopCount;
ByteArrayOutputStream tokenBuffer = new ByteArrayOutputStream();
loopCount = 0;
// The following would not find the end of the file.
// do {
// loopCount++;
// tokenBuffer.write(nextByte);
// byte[] currentToken = tokenBuffer.toByteArray();
// } while ((nextByte = in.read()) != -1);
// Alternate code for the above.
nextByte = in.read();
while (nextByte != -1){
log.error("Next byte is: " + nextByte);
loopCount++;
tokenBuffer.write(nextByte);
// Last byte would act like it is looping, but is not (set breakpoint property
// and paused and loopCount remains the same), no errors displayed.
nextByte = in.read();
}
byte[] currentToken = tokenBuffer.toByteArray();
if (currentToken.length > 0) {
byte[] token = new byte[currentToken.length];
System.arraycopy(currentToken, 0, token, 0, currentToken.length);
return token;
}
return null;
}