UTF-8问题

chrischen79 2002-04-01 02:18:27
问题简述:汉字字符串在gb2312和utf-8编码之间的转换,我是用了类似于gb2312和iso-8859-1编码转化的方法,结果对中文字符无效

参考以下例子程序:

public class test {
public static void main(String[] args) {
toUTF8("abc");
toUTF8("汉字");
}

static void toUTF8(String s){
System.out.println("Source string: "+s);
try{
s = new String(s.getBytes(), "UTF8");
byte[] bytes = s.getBytes("UTF8");
System.out.println("length: "+bytes.length);
}catch(java.io.UnsupportedEncodingException uee){
uee.printStackTrace();
}
}
}

输出:
Source string: abc

length: 3

Source string: 汉字

length: 0


我发现中文string从gb2312转化到utf-8后,成了一个空string

中文win2000+jb6,系统默认编码GBK
...全文
43 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
chrischen79 2002-04-02
  • 打赏
  • 举报
回复
各位帮我看看
chrischen79 2002-04-01
  • 打赏
  • 举报
回复
那我要是把中文字符编码成utf8写入数据库,再读出数据显示在jsp页面上

怎么做
cooleyes 2002-04-01
  • 打赏
  • 举报
回复
public byte[] getBytes(String enc)
throws UnsupportedEncodingException
Convert this String into bytes according to the specified character encoding,
storing the result into a new byte array.
这个函数是将字符串按指定的编码方案编码,返回其编码
所以,想知道字符串的UTF8编码的话,可以使用getBytes("UTF8")
byte[] bytes = "中文".getBytes("UTF8");
System.out.println("length: "+bytes.length);
>>length: 6

chrischen79 2002-04-01
  • 打赏
  • 举报
回复
我明白了一些:自己对String的getByte()理解有误。先给出一些分数,等我系统测试之后结帐。

先谢谢各位了
家有笨狗 2002-04-01
  • 打赏
  • 举报
回复
new String(s.getBytes(fromCode),toCode);
zha1977 2002-04-01
  • 打赏
  • 举报
回复
不多那个new也不成,我很早以前就试过了,得到一个空串
最后只好自己写了个方法
idpmud 2002-04-01
  • 打赏
  • 举报
回复
应该直接
byte[] bytes = s.getBytes("UTF8");
你多了一个NEW所以才这样,字符转换时不需要的。
长度这样是4。
wangtaoyy 2002-04-01
  • 打赏
  • 举报
回复
http://www.csdn.net/expert/topic/589/589476.xml?temp=.701214
zjp009 2002-04-01
  • 打赏
  • 举报
回复

static void toUTF8(String s)
{
System.out.println("Source string: "+s);
try
{
byte[] bytes = s.getBytes("ISO-8859-1");
String strReturn = new String(bytes,"UTF-8");
System.out.println(strReturn);
System.out.println( "length: "+strReturn.length() );
}
catch(java.io.UnsupportedEncodingException uee)
{
uee.printStackTrace();
}
}
GJA106 2002-04-01
  • 打赏
  • 举报
回复
try{
s = new String(s.getBytes(), "UTF8");
byte[] bytes = s.getBytes("UTF8");
System.out.println("length: "+bytes.length);
}catch(java.io.UnsupportedEncodingException uee){
uee.printStackTrace();
}


改为:
try{
s = new String(s.getBytes(), "GBK");
byte[] bytes = s.getBytes("UTF8");
System.out.println("length: "+bytes.length);
}catch(java.io.UnsupportedEncodingException uee){
uee.printStackTrace();
}
看看。

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧