当前位置: 技术问答>java相关
编码问题请教
来源: 互联网 发布时间:2015-04-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 ...
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");
//为何不能还原,如何做?
}
|
不是所用字符都能相互转换,
byte[] bs = str.getBytes("8859_1")即unicode到8859_1将失真,具体的说由于汉字的unicode码超出8859_1的表达范围,被视为不合法字符,转换成63。
byte[] bs = str.getBytes("unicode")和
byte[] bs = str.getBytes("gb2312")不会失真
byte[] bs = str.getBytes("8859_1")即unicode到8859_1将失真,具体的说由于汉字的unicode码超出8859_1的表达范围,被视为不合法字符,转换成63。
byte[] bs = str.getBytes("unicode")和
byte[] bs = str.getBytes("gb2312")不会失真
|
尝试将他们写到文件里,在打开文件看看有什么不同。
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
}
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
}