项目里想改一个中文乱码问题,我把问题提取出来,写了个类.public class Test {
public static void main(String[] args)
{
String ys = "A日"; //原始字符串
String str;
try{
byte [] b = ys.getBytes("US-ASCII");
char [] c = new char[b.length];
for(int x = 0;x<b.length;x++)
{c[x] = (char) b[x];}
str = String.valueOf(c);
//******ys是按US-ASCII字符集转的,只能利用byte数组b或者字符串str.想获得中文的字符串str1输出.ps:我试过str1 = new String(b,"GBK"),不知道为什么不行,这是我最困惑的.
也是过 str1 = new String(str.getBytes("US-ASCII"),"GBK");
所以提出这两个解决方法的朋友先看看,这两个不行的....
public static void main(String[] args)
{
String ys = "A日"; //原始字符串
String str;
try{
byte [] b = ys.getBytes("US-ASCII");
char [] c = new char[b.length];
for(int x = 0;x<b.length;x++)
{c[x] = (char) b[x];}
str = String.valueOf(c);
//******ys是按US-ASCII字符集转的,只能利用byte数组b或者字符串str.想获得中文的字符串str1输出.ps:我试过str1 = new String(b,"GBK"),不知道为什么不行,这是我最困惑的.
也是过 str1 = new String(str.getBytes("US-ASCII"),"GBK");
所以提出这两个解决方法的朋友先看看,这两个不行的....
new String(str.getBytes("ISO-8859-1"),"GBK");
偶以前碰到过,可以行得通
String ys = "A日"; // 原始字符串
String str;
try {
// byte[] b = ys.getBytes("US-ASCII");
byte[] b = ys.getBytes("GBK");
// char[] c = new char[b.length];
byte[] c = new byte[b.length];
for (int x = 0; x < b.length; x++) {
c[x] = b[x];
}
// str = String.valueOf(c);
str = new String(b,"GBK");
System.out.println(str);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
汉字是占两个字节的,:也就是
String ys = "A日";
byte [] b = ys.getBytes("US-ASCII");
//此时b 的length应该是 3
而char[] c=ys.toCharArray();
此时c的length应该是 2
一个字符点两个字节,所以char是可以放汉字的,(汉字就占两个字节),而你写的程序是把一个汉字拆成两个字节了,然后再把这两个单独的字节又转换成char,那么就生成了共三个char,应该是两个char啊,你说能不错吗???
楼上的又创建了一个byte数组,与源数组一样,又写个循环,没多大意义吧,b 与 c 一样啊,写他干什么
byte [] b = ys.getBytes("US-ASCII");
1、在网页中输出中文。
JAVA在网络传输中使用的编码是"ISO-8859-1",故在输出时需要进行转化,如:
String str="中文";
str=new String(str.getBytes("GB2312"),"8859_1");
但假如在编译程序时,使用的编码是“GB2312”,且在中文平台上运行此程序,不会出现此问题,一定要注重。
2、从参数中读取中文
这正好与在网页中输出相反如:
str=new String(str.getBytes("8859_1"),"GB2312");
3、操作DB中的中文问题
一个较简单的方法是:在“控制面扳”中,把“区域”设置为“英语(美国)”。假如还会出现乱码,还可进行如下设置:
取中文时:str=new String(str.getBytes("GB2312"));
向DB中输入中文:str=new String(str.getBytes("ISO-8859-1")); 4、在jsp中的中文解决: 在“控制面扳”中,把“区域”设置为“英语(美国)”.
在JSP页面中加入:
假如还不行正常显示,则还要进行下面的转换:
如:name=new String(name.getBytes("ISO-8859-1"),"GBK");
就不会出现中文问题了。