2014-02-10 19 views
2

完全支持下面我有一个小的测试程序比可以验证,如果一个字符串的内容全在代码页 CP852或不支持。有没有更好的方法来做到这一点?验证一个字符串是否在一个特定的代码页

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

输出:

æøå123 
???123 
String supported in codepage: false 

回答

1

您可以创建一个编码器对应的字符集,并明确使用its canEncode method

boolean canEncode = Charset.forName("CP852").newEncoder().canEncode(test); 
+0

只是辉煌! –

相关问题