views:

451

answers:

3

Hello,

I am trying this:

byte[] b = String.getByte("ASCII") and get an UnsupportedEncodingException Exception

String fName = new String(b,"ASCII");

- got the same when used

byte[] b = String.getByte("ISO8859_1");
String fName = new String(b,"ISO8859_1");

Appreciate any help.

+7  A: 

That code won't compile - it's String.getBytes() not String.getByte(), and it's an instance method not a static method. It's always worth cutting and pasting a real example which you've got working (even if it's just a dummy app).

However, assuming you've got similar code which is compiling, you should be using "US-ASCII" and "ISO-8859-1" as the names, as documented in the Charset JavaDoc.

Jon Skeet
+1 good catch on String.getByte
dfa
u r right. it's getBytes. My mistake on the question. Still it does explain why i am getting this exception (other CharSets i tried are US-ASCII)
andreas
The problem with typos in the question is that it's not clear which errors are transcription errors (like getByte/getBytes) and which are *real* errors. Did you *really* have "US-ASCII" or "ASCII"?
Jon Skeet
Reminds me of a bug I spent an hour or so trying to figure out. It turns out that I was calling `new String(bytes, "\"UTF-8\"")`. The exception message showed the quotes, but of course it didn't click that they were part of the actual encoding name. Duh!
Stephen C
FYI, "ASCII" is a valid alias for "US-ASCII".
Alan Moore
@Alan M: It may be on some JREs, but it's not in the list of *guaranteed* ones. It's perfectly possible that andreas' JRE doesn't support that alias.
Jon Skeet
A: 

according to javadoc you must use: "US-ASCII"

dfa
+2  A: 

I think you want something more like this:


import java.io.UnsupportedEncodingException;


public class Encoding
{
    public static void main(String[] args) throws UnsupportedEncodingException
    {
     String s = "Hello world";
     byte[] b = s.getBytes("US-ASCII");
    }
}

Simon Nickerson
In other words, @andreas, the problem isn't that the code is **throwing** an exception, it's that you're not **catching** one. Your code wasn't even compiling because you weren't handling that checked exception.
Alan Moore
@Alan M: How did you draw that conclusion? Where does the question say that the code doesn't compile? Andreas says he "gets" an exception, but not whether it's at execution time or compile time.
Jon Skeet