dcsimg
Character conversion
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Sanjay_Mistry
Posted On:   Thursday, May 17, 2001 08:13 AM

I want to send some text to client, which supports only ASCII not Unicode.

How can I conver Unicode to ASCII and ASCII to Unicode !

Re: Character conversion

Posted By:   Alistair_Sheffield  
Posted On:   Thursday, May 17, 2001 09:04 AM

What do you mean by 'send' and 'support'?


Since you've posted this in the RMI Forum, does that mean you're using RMI? I thought RMI was a Java technology, so if the client is Java it should have no problem understanding Unicode.


However, until you give some more details, I can't give you a very detailed answer. I can tell you how to get hold of some bytes which represent ASCII characters, though.


String s = "This is a string";
byte[] asciiBytes = s.getBytes("ASCII");

asciiBytes will then contain the bytes which represent the contents of the String s in ASCII character encoding. The argument to getBytes() is the encoding to convert the String to. Note that because all String objects in Java use Unicode, you can't have a String which holds anything but Unicode characters - that's why you have to convert the String to bytes.


Another way of achieving the same thing is with OutputStreamWriter. You can construct one of these with an encoding to convert to, and then just write characters to it, like this:


FileOutputStream fOut = new FileOutputStream("ascii.txt");
OutputStreamWriter asciiWriter = new OutputStreamWriter(fOut, "ASCII");
asciiWriter.write("This is some ascii");

Note that I haven't put any exception handling code in - this is only an example! After you've flushed and closed the streams, you should have a text file containing ASCII.


I suspect that the OutputStreamWriter will be more useful to you than the getBytes() method: you might be able to get hold of a stream to the client you want to send ASCII to, and then you can just wrap that stream in an OutputStreamWriter as above.


Note, however, that because ASCII cannot encode all Unicode characters, only the first 128, funny things may happen if the text you're converting contains any characters outside those ASCII can represent. I don't know what will happen to those - I suspect they'll get split in half and you'll end up with two ASCII characters in place of the one Unicode one, but you'd have to test that.


Sorry I couldn't be more useful - if you want more help, get back to me with some specifics.


Alistair

About | Sitemap | Contact