编码问题请教

AYellow 2002-03-20 07:34:20

public static void main(String[] args)throws Exception{
String str = "中文";
String str2;
String str3;

str2 = new String(str.getBytes("8859_1"),"gb2312");
//变成乱码

str3 = new String(str.getBytes("gb2312"),"8859_1");
//为何不能还原,如何做?
}
...全文
31 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
skyyoung 2002-03-22
  • 打赏
  • 举报
回复
尝试将他们写到文件里,在打开文件看看有什么不同。
public void writeFile(String str, String filename) throws Exception
{
// Open a writer to the file, then write the string.
BufferedWriter bwriter;//writer to the file
String fullfilepath;//path for the output file
try
{
bwriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
bwriter.write(str);
bwriter.flush();
bwriter.close();
}//try
catch(Exception e)
{
throw e;
}//catch
}
wangtaoyy 2002-03-22
  • 打赏
  • 举报
回复
不是所用字符都能相互转换,
byte[] bs = str.getBytes("8859_1")即unicode到8859_1将失真,具体的说由于汉字的unicode码超出8859_1的表达范围,被视为不合法字符,转换成63。
byte[] bs = str.getBytes("unicode")和
byte[] bs = str.getBytes("gb2312")不会失真



chrischen79 2002-03-21
  • 打赏
  • 举报
回复
public static void main(String[] args)throws Exception{
String str = "中文";
String str2;
String str3;

str2 = new String(str.getBytes("8859_1"),"gb2312");
//变成乱码

str3 = new String(str.getBytes("gb2312"),"8859_1");
^^^
//为何不能还原,如何做?
}

还原部分的代码写错了,str2.getBytes...才对
snowredfox 2002-03-21
  • 打赏
  • 举报
回复

str2 = new String(str.getBytes("8859_1"),"gb2312");
编码后,str2并没有包含任何的编码信息,已经转换成了一些ASCII自符.我觉得这种不包含编码信息的字符是不可能解得出来的

关注,:P
AYellow 2002-03-21
  • 打赏
  • 举报
回复
楼上老兄仍然答非所问
wangtaoyy 2002-03-20
  • 打赏
  • 举报
回复
应该这样吧
public class Test{
public static void main(String[] ar) throws Exception{
String str1 = "中文";
String str2;
String str3;
//变成乱码
str2 = new String(str1.getBytes("gb2312"), "8859_1");

//恢复
str3 = new String(str2.getBytes("8859_1"), "gb2312");
//为何不能还原,如何做?

System.out.println(str1);
System.out.println(str2);
System.out.println(str3);



}
}
AYellow 2002-03-20
  • 打赏
  • 举报
回复
楼上老兄的代码没有问题,但不是我想要的。
我想知道经过
str2 = new String(str.getBytes("8859_1"),"gb2312");
的转换以后,如何还原?
xhh 2002-03-20
  • 打赏
  • 举报
回复
用这个试试:
public static void main(String[] args)throws Exception{
String str1 = "中文";
String str2;
String str3;
str2 = new String(str1.getBytes("unicode"), "8859_1");
//变成乱码
str3 = new String(str2.getBytes("8859_1"), "unicode");
//为何不能还原,如何做?
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
wobensuren 2002-03-20
  • 打赏
  • 举报
回复
这是java中的 中文处理问题吗!

62,614

社区成员

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

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