Advice on InputStream reading
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Blake_Minghelli
Posted On:   Friday, January 24, 2003 01:29 PM

I am currently developing an application that uses a modem (external serial modem) for dial-up connection (9600 baud rate) to an external service. I'm using the javax.comm package. My question is: What is the best way to determine when there is no more data to read from the InputStream? The sample code that I've seen has done something like this: int noReadCount = 0; while (true) { int numBytes = inputStream.read(readBuffer); if (numBytes == 0) { noReadCount++; } else { noReadCount = 0; } // if no bytes for 5 attempts then assume we've // received all data if (noReadCount > 4) { break; }    More>>

I am currently developing an application that uses a modem (external serial modem) for dial-up connection (9600 baud rate) to an external service. I'm using the javax.comm package.


My question is: What is the best way to determine when there is no more data to read from the InputStream?


The sample code that I've seen has done something like this:


			
int noReadCount = 0;
while (true) {
int numBytes = inputStream.read(readBuffer);
if (numBytes == 0) {
noReadCount++;
} else {
noReadCount = 0;
}
// if no bytes for 5 attempts then assume we've
// received all data
if (noReadCount > 4) {
break;
}
// Sleep for a second before trying to read again
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
}


(That code's not exact but close enough)


It seems like there must be a more efficient way of doing that.

Any advice or comments are appreciated.    <<Less

Re: Advice on InputStream reading

Posted By:   Stephen_Ostermiller  
Posted On:   Tuesday, January 28, 2003 03:15 PM

I don't know about the input stream from the package that you are using, but in general the read() methods of an input stream are supposed to return -1 when there will be no more data available.


According to The InputStream API, read() is only supposed to return zero under some very special circumstances. If you encounter a stream that is returning zeros, there is probably some bug in it. Usually when I read from a stream I say:


int amountRead;
while ((amountRead = inputStream.read(readBuffer)) != -1){
// got amountRead bytes of data (possibly zero)
}

Re: Advice on InputStream reading

Posted By:   Blake_Minghelli  
Posted On:   Friday, January 24, 2003 01:47 PM

oops, I realize I have a bug in line 3. Please replace it with:



int numBytes = inputStream.read(buffer, totalRead, buffer.length - totalRead);
About | Sitemap | Contact