Question

Below I have a small test program than can verify if the content of a String is full supported in codepage CP852 or not. Is there a more elegant way of doing this?

public class CodepageTest {
    public static void main(String[] args) {
        try {
            String test = "æøå123";
            String test2 = new String(test.getBytes("CP852"), "CP852");

            System.out.println(test);
            System.out.println(test2);

            System.out.println("String supported in codepage: " + (test.equals(test2)));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

Output:

æøå123
???123
String supported in codepage: false
Was it helpful?

Solution

You could create an encoder corresponding to your charset explicitly and use its canEncode method:

boolean canEncode = Charset.forName("CP852").newEncoder().canEncode(test);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top