2

Is there a way to find out if an encoding is supported or not? E. g. a method like this:

isSupported("UTF-8") == true

and

isSupported("UTF-13") == false

I need this to validate if the Content-Disposition-Header of my MimeMessages is correct.

2 Answers 2

11

Try the following:

Charset.isSupported("UTF-8")

this method may throw RuntimeExceptions when name is null or the name is invalid.

Sign up to request clarification or add additional context in comments.

3 Comments

+1, How could I have overlooked that in Javadoc... Still, it could throw a IllegalCharsetNameException if the given charset name is illegal
@jlordo As I wrote it can throw a RuntimeException when the name is invalid.
The typo I fixed in your answer (of/or) confused me..., sorry.
6
boolean isCharsetSupported(String name) {
  try {
    Charset.forName(name);
    return true;
  } catch (UnsupportedCharsetException | IllegalCharsetNameException | IllegalArgumentException e) {
    return false;
  }
}

or without a try/catch block:

boolean isCharsetSupported(String name) {
    return Charset.availableCharsets().keySet().contains(name);
}

2 Comments

I've hoped for something without exceptions, but thanks anyway ;)
Using Exceptions as flow control is discouraged in Java.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.