编码问题请教
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");
//为何不能还原,如何做?
}
问题点数:50、回复次数:9Top
1 楼wobensuren(丑得杀死你)回复于 2002-03-20 20:01:17 得分 0
这是java中的 中文处理问题吗!Top
2 楼xhh(霹雳游侠)回复于 2002-03-20 20:07:09 得分 0
用这个试试:
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);
}Top
3 楼AYellow((北斗猪)(AreYouOK?))回复于 2002-03-20 20:47:11 得分 0
楼上老兄的代码没有问题,但不是我想要的。
我想知道经过
str2 = new String(str.getBytes("8859_1"),"gb2312");
的转换以后,如何还原?Top
4 楼wangtaoyy(flow)回复于 2002-03-20 21:27:02 得分 0
应该这样吧
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);
}
}
Top
5 楼AYellow((北斗猪)(AreYouOK?))回复于 2002-03-21 16:45:50 得分 0
楼上老兄仍然答非所问Top
6 楼snowredfox(〓〓鹤舞白沙,笑骂风云淡〓〓)回复于 2002-03-21 17:48:40 得分 0
在
str2 = new String(str.getBytes("8859_1"),"gb2312");
编码后,str2并没有包含任何的编码信息,已经转换成了一些ASCII自符.我觉得这种不包含编码信息的字符是不可能解得出来的
关注,:PTop
7 楼chenyuan_tongji(codeguru)回复于 2002-03-21 17:55:03 得分 0
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...才对Top
8 楼skyyoung(路人甲)回复于 2002-03-22 09:19:01 得分 20
尝试将他们写到文件里,在打开文件看看有什么不同。
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
}Top
9 楼wangtaoyy(flow)回复于 2002-03-22 20:12:01 得分 30
不是所用字符都能相互转换,
byte[] bs = str.getBytes("8859_1")即unicode到8859_1将失真,具体的说由于汉字的unicode码超出8859_1的表达范围,被视为不合法字符,转换成63。
byte[] bs = str.getBytes("unicode")和
byte[] bs = str.getBytes("gb2312")不会失真
Top




