首页 > Java > Java编码转换-内存中字符串编码转换实例

Java编码转换-内存中字符串编码转换实例

2010年7月10日 admin 发表评论 阅读评论

Java编程时会遇到很多字符集编码转换的问题,当读取的字符在内存中如何执行编码转换?下面给出一个实例

  1. import java.nio.ByteBuffer;
  2. import java.nio.charset.Charset;
  3. public class MainClass {
  4. public static void main(String[] argv) throws Exception {
  5. String input = ”\u00bfMa\u00f1ana?”;
  6. // The list of charsets to encode with
  7. String[] charsetNames = { ”US-ASCII”, ”ISO-8859-1″, ”UTF-8″, ”UTF-16BE”, ”UTF-16LE”, ”UTF-16″,
  8. // ”X-ROT13″ // This requires META-INF/services
  9. };
  10. for (int i = 0; i < charsetNames.length; i++) {
  11. doEncode(Charset.forName(charsetNames[i]), input);
  12. }
  13. }
  14. private static void doEncode(Charset cs, String input) {
  15. ByteBuffer bb = cs.encode(input);
  16. System.out.println(“Charset: ” + cs.name());
  17. System.out.println(“  Input: ” + input);
  18. System.out.println(“Encoded: ”);
  19. for (int i = 0; bb.hasRemaining(); i++) {
  20. int b = bb.get();
  21. int ival = ((int) b) & 0xff;
  22. char c = (char) ival;
  23. // print index number
  24. System.out.print(“  ” + i + ”: ”);
  25. // print the hex value of the byte
  26. System.out.print(Integer.toHexString(ival));
  27. System.out.println(“ (“ + c + ”)”);
  28. }
  29. }
  30. }

java

相关日志

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.
Easy AdSense by Unreal