|
|
Java编程技术中汉字问题分析及解决
来源:精英教育网综合 更新时间:2008-4-15 http://www.edu5a.com | | 精英教育阅读提示:现在 Java 编程语言已经广泛应用于互联网世界,早在 Sun 公司开发 Java 语言的时候,就已经考虑到对非英文字符的支持了。Sun 公司公布的 Java 运行环境(JRE)本身就分英文版和国际版,但只有国际版才支持非英文字符。 |
|
然后系统的缺省编码方式为“8859-1”。
2.如果在转换字符串时不采用系统缺省编码方式,而是直接采用 “GBK” 或“GB2312”,则在 A 情况下程序仍然可正常运行,在 B 情况下,系统出现错误:
UnsupportedEncodingException。
3.在客户机上,把 JDK 的 CLASSES.ZIP 解压后,放在另一个目录中, CLASSPATH 只包含该目录。然后一边逐步删除该目录中的 .CLASS 文件,另一边运行测试程序,最后发现在一千多个 CLASS 文件中,只有一个是必不可少的,该文件是:
sun.io.CharToByteDoubleByte.class。
将该文件拷到服务器端和其它的类放在一起,并在程序的开头 IMPORT 它,在 B 情况下程序仍然无法正常运行。
4.在 A 情况下,如果在 CLASSPTH 中去掉 sun.io.CharToByteDoubleByte.class ,则程序运行时测得默认编码方式为“8859-1”,否则为 “GBK” 或 “GB2312” 。
如果 JDK 的版本为1.2以上的话,在 B 情况下遇到的问题得到了很好的解决,测试的步骤同上,有兴趣的读者可以尝试一下。
Java 中文问题的根源分析及解决
在简体中文 MS Windows 98 + JDK 1.3 下,可以用 System.getProperties() 得到 Java 运行环境的一些基本属性,类 PoorChinese 可以帮助我们得到这些属性。
类 PoorChinese 的源代码:
public class PoorChinese {}
执行 java PoorChinese 后,我们会得到:
系统变量 file.encoding 的值为 GBK ,user.language 的值为 zh , user.region 的值为 CN ,这些系统变量的值决定了系统默认的编码方式是 GBK 。
在上述系统中,下面的代码将 GB2312 文件转换成 Big5 文件,它们能够帮助我们理解 Java 中汉字编码的转化:
import java.io.*; import java.util.*; public class gb2big5 { static int iCharNum=0; public static void main(String[] args) { System.out.println("Input GB2312 file, output Big5 file."); if (args.length!=2) { System.err.println("Usage: jview gb2big5 gbfile big5file"); System.exit(1); String inputString = readInput(args[0]); writeOutput(inputString,args[1]); System.out.println("Number of Characters in file: "+iCharNum+"."); } static void writeOutput(String str, String strOutFile) { try { FileOutputStream fos = new FileOutputStream(strOutFile); Writer out = new OutputStreamWriter(fos, "Big5"); out.write(str); out.close(); } catch (IOException e) { e.printStackTrace(); e.printStackTrace(); } } static String readInput(String strInFile) { StringBuffer buffer = new StringBuffer(); try { FileInputStream fis = new FileInputStream(strInFile); InputStreamReader isr = new InputStreamReader(fis, "GB2312"); Reader in = new BufferedReader(isr); int ch; while ((ch = in.read()) > -1) { iCharNum += 1;buffer.append((char)ch); } in.close(); return buffer.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } } | 编码转化的过程如下:
GB2312------------------>Unicode------------->Big5
执行 java gb2big5 gb.txt big5.txt ,如果 gb.txt 的内容是“今天星期三”,则得到的文件 big5.txt 中的字符能够正确显示;而如果 gb.txt 的内容是“情人节快乐”,则得到的文件 big5.txt 中对应于“节”和“乐”的字符都是符号“?”(0x3F),可见 sun.io.ByteToCharGB2312 和 sun.io.CharToByteBig5 这两个基本类并没有编好。 |
|
|
|
|
上一篇:运用数据仓库技术分析Web日志 下一篇:Java 泛型的理解与等价实现 |
|
| 相关新闻 |
|
|
|
|