tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Len Popp" <len.p...@gmail.com>
Subject Re: [OT] Basic int/char conversion question
Date Thu, 01 Jan 2009 21:23:05 GMT
On Thu, Jan 1, 2009 at 14:39, André Warnier <aw@ice-sa.com> wrote:
> I note with satisfaction that I'm not the only one laboring away on this
> day-after, but you're just all going a bit too fast for me and my growing
> but still limited Java knowledge.

No hang-over here. :-)

> In other words, in order to keep my changes and post-festivities headaches
> to a minimum, I would like to keep buf being a StringBuffer. So what I was
> really looking for was the correct alternative to
>          buf.append((char) ic);
> which would convert ic from an integer, to the appropriate Unicode
> character, taking into account the "knownEncoding" which I know.
>
> Does that not exist ?

(I'll leave the InputStreamReader explanation to Chuck.)

I was guessing that the StringBuffer would soon be converted to a
String (which is the usual case). If not …

I don't see a simple one-line way to convert one byte to a character
in a given charset. It looks like String and CharsetDecoder are the
classes you're supposed to use. If there's an easy way to convert a
single character, someone please point it out.

How about this: Read the bytes as bytes, convert them to a String in
the correct charset, and create a StringBuffer from that. Like so:

  String knownEncoding = "ISO-8859-1"; // or "ISO-8859-2"
  InputStreamReader fromApp;
  fromApp =  = new InputStreamReader(socket.getInputStream(),
  int ic = 0;
  ByteBuffer inbuf = ByteBuffer.allocate(2000);
  while((ic = fromApp.read()) != 26 && ic != -1) // hex 1A (SUB)
           inbuf.put((char)ic);
  byte[] inbytes = new byte[inbuf.limit()];
  inbuf.get(inbytes);
  String s = new String(inbytes, knownEncoding);
  StringBuffer buf = new StringBuffer(s);

(I haven't tested this so it might not be correct.)
It's not very efficient but it keeps the changes in one place.
-- 
Len
Mime
View raw message