woezelmann
woezelmann

Reputation: 1395

Check programmatically if encoding is supported

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.

Upvotes: 2

Views: 2356

Answers (2)

Uwe Plonus
Uwe Plonus

Reputation: 9964

Try the following:

Charset.isSupported("UTF-8")

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

Upvotes: 11

jlordo
jlordo

Reputation: 37833

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);
}

Upvotes: 6

Related Questions