寫出來的文件用瀏覽器打開后都是亂碼。已經在XML的最前面加上了
<?xml version="1.0" encoding="UTF-8"?>
而且瀏覽器的編碼也是UTF-8的,這就排除了瀏覽器的問題。
再用VIM打開,發現用GB2312看是沒問題的,換成:set encoding=UTF-8以后開始亂碼
這時我嘗試將字符串轉碼后寫入文件,但在UTF-8,GBK和ISO8859_1中間怎么轉也沒有用。
忽然想起前幾天yiyayoyo同學和我提過Java寫文件默認編碼的問題,于是開始google,發現我用的寫文件的方式無法指定編碼,于是換用另一種寫文件的方式指定UTF-8,遂搞定。代碼如下:
老代碼:
PrintWriter pw = new PrintWriter(new FileWriter(path));
pw.print(content);
pw.close();
新代碼:
FileOutputStream fos = new FileOutputStream(path);
Writer out = new OutputStreamWriter(fos, "UTF-8");
out.write(content);
out.close();
fos.close();
順便抱怨一句,Java中寫文件的方式還真是多阿多……我等一兩年經驗的小程序員看了都眼暈
庫卡 說:
讀代碼也有編碼的問題,如果要讀取UTF-8的文件,應采用如下方式覆蓋默認編碼:
FileInputStream fis = new FileInputStream(s);
StringBuffer content = new StringBuffer();
DataInputStream in = new DataInputStream(fis);
BufferedReader d = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line = null;
while ((line = d.readLine()) != null)
content.append(line + "\n");
d.close();
in.close();
fis.close();
posted on 2008-02-14 14:20
lk 閱讀(799)
評論(0) 編輯 收藏 所屬分類:
j2se 、
xml