将汉字转为UTF-8编码

01./**
02. * 将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名.
03. * @param s 原文件名
04. * @return 重新编码后的文件名
05. */
06.public String toUtf8String(String s) {
07. if (s == null || s.equals("")) {
08. return null;
09. }
10. StringBuffer sb = new StringBuffer();
11. try {
12. char c;
13. for (int i = 0; i < s.length(); i++) {
14. c = s.charAt(i);
15. if (c >= 0 && c <= 255) {
16. sb.append(c);
17. } else {
18. byte[] b;
19. b = Character.toString(c).getBytes("utf-8");
20. for (int j = 0; j < b.length; j++) {
21. int k = b[j];
22. if (k < 0)
23. k += 256;
24. sb.append("%" + Integer.toHexString(k).toUpperCase());
25. }
26. }
27. }
28. } catch (Exception e) {
29. e.printStackTrace();
30. }
31. return sb.toString();
32.}
上一篇:Swift开发学习(两):Playground


下一篇:Codeforces Round #310 (Div. 1) C. Case of Chocolate (线段树)