J2ME and serial port

C

caimaani

Hi,

I am developing J2ME class that listens the serial port and reads all
available bytes from the buffer in a single read event. The number of
bytes and the structure of the message may vary very much (read: they
are undefined).

At the time I'm using InputStream.read() method to read the first byte
and to trigger InputStream.available() to find out how many bytes the
buffer still contains before I read them all. However it seems not to
be very reliable without some kind of delay because sometimes the
bytes are written to buffer so slowly (althought another component
does this in a single write event). So reading is triggered too
quickly and available() returns too small number.

How can I ensure that InputStream.available() gives me the real number
of bytes? Is it mandatory to add some kind of delay?
 
D

Darryl Pierce

caimaani said:
At the time I'm using InputStream.read() method to read the first byte
and to trigger InputStream.available() to find out how many bytes the
buffer still contains before I read them all.

Don't use InputStream.available(). Instead, keep reading from the input
stream until it returns a value of -1 (EOF).

How can I ensure that InputStream.available() gives me the real number
of bytes? Is it mandatory to add some kind of delay?

No, and there's no way to know for sure. Your best bet is to read data
from the input stream and write that data to an instance of
ByteArrayOutputStream. Then, when you've finished, you can retrieve that
data as an array of bytes from the ByteArrayOutputStream. Here's an
example of how to do it:

public byte[] readData(InputStream istream) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new buffer[4096];
int read = istream.read(buffer);

while(read != -1)
{
baos.write(buffer,0,read);
read = istream.read(buffer);
}

return baos.toByteArray();
}

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top