I'm using the MIDP 2.0 (JSR 118) and I just noticed that there is no reader for strings in J2ME.
Does anyone know how you are supposed to read Strings from an InputStream
or InputStreamReader
in a platform independent way (i.e. between two java enabled cell phones of different models)?
Which profile are you using? The MID profile in JSR 118 specifies InputStreamReader (not StringReader, but that wouldn't help you read from an InputStream anyway).
EDIT: To reflect the change to the question :)
You use InputStreamReader.read(char[], int, int) and when you've read all you want to, create a new string from a char array. If you want to read a line at a time as you would from BufferedReader, you basically need to implement the functionality of BufferedReader yourself (keeping a buffer of "read but not consumed" chars) and keep reading until you hit a line break.
Would you be able to provide an example of this?
You use
InputStreamReader.read(char[], int, int)
and when you've read all you want to, create a new string from a char array. If you want to read a line at a time as you would fromBufferedReader
, you basically need to implement the functionality of BufferedReader yourself (keeping a buffer of "read but not consumed" chars) and keep reading until you hit a line break.Alternatively have a look at
DataInputStream.readUTF()
.It does required that the string being read off the InputStream be encoded appropriately (as in by a corresponding
DataOutputStream.writeUTF(String)
) so it might not be what you're looking for - but it does work across different phones/models etc.Well... I know this was a LONG time ago.
You need to do exactly what John said, and it is VERY simple. It almost took me 5 hours to figure this one out the first time...
I still wonder why j2ME didn't include something as essential as the
BufferedReader
method for sockets, it's not like the freakin cellphones will crash with it... and yes, I don't give a rat's ass if my app runs 1ms slower than it should.(I'm just going to put the relevant code, I assume you know how to form classes and import the required libraries)
As you can see, the
is.read()
method will lock the thread till new input is received from the user ONE BYTE AT A TIME. This means if you use telnet to test, each keystroke will make the loop iterate once, hence, we simply concatenate char by char in aStringBuffer
until char 13 is received.I hope this helps people trying to do a socket server on j2ME. I already crafted a fully functional multithreaded version of this for blackberry, in case anyone needs it.