Java開發亂碼問題

wKioL1TE5LrTU4_mAAB7SXbfC14664.jpg

public class DemoEncoding {
public static void main(String[] args) throws IOException {
String data = "中國";
// 編碼
byte[] bytes = data.getBytes("gbk");
// 正確解碼
String result1 = new String(bytes, "gbk");
System.out.println("result1="+result1);// --中國
// 錯誤解碼
String result2 = new String(bytes, "utf-8");
System.out.println("result2="+result2);// --?й?
//解錯碼
byte[] bytes1 = data.getBytes();
// 用正確的碼錶解碼
String result3 = new String(bytes1, "utf-8");
System.out.println("result3="+result3);// --中國
 
//編錯了碼 失敗徹底
byte[] bytes2 = data.getBytes("iso-8859-1");
System.out.println(bytes2[1]);//63
String result4 = new String(bytes2, "gbk");
System.out.println("result4="+result4);//??
 
//
String path = DemoEncoding.class.getClassLoader().getResource("a.txt").getPath();
//FileReader默認使用gbk
FileReader fileReader = new FileReader(path);
char[] buffer = new char[10];
int len = fileReader.read(buffer);
System.out.println(new String(buffer,0,len));//中國
 
Reader reader = new InputStreamReader(new FileInputStream(path),"utf-8");
char[] buff = new char[10];
int len1 = reader.read(buff);
System.out.println(new String(buff,0,len1));//中國
 
//結論 全部出現 ????? 即 63 表示編錯碼
//出現 其他怪異中文是解錯碼
}
}

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章