java轉換流亂碼問題

public static voidmain(String args[]) {

FileInputStream fis =null;

FileOutputStream fox =null;

OutputStreamWriter osw =null;

InputStreamReader inputStreamReader =null;

try{

fis =newFileInputStream("F:\\a.txt");

/** 前提:當您要write數據時,要先確保read的數據不是亂碼的,不然write後的數據怎麼該編碼格式都會是亂碼的,因爲它的本質已經是亂碼的了

*因爲我的IDEA的默認編碼是UTF-8

,所以inputStreamReader的編碼也是UTF-8;而記事本的編碼是ANSI

*即是系統默認編碼GBK,所以要指定GBK的編碼格式讀取 ,而如果您的編輯器默認的編碼格式是GBK,那麼不指定編碼格式也不會亂碼

*/

inputStreamReader =newInputStreamReader(fis,"GBK");

fox =newFileOutputStream("F:\\b.txt");

osw =newOutputStreamWriter(fox,"GBK");

char[] bytes =new char[64]; //因爲inputStreamReader讀取的是字符數組,而如果讀取的是字節數組,纔會構建一個字節數組

while((inputStreamReader.read() != -1)) {

intread = inputStreamReader.read(bytes); 

osw.write(newString(bytes,0,read));  //將字符數組轉成字符串,進而write字符數據

System.out.println(newString(bytes,0,read));

osw.flush();//要刷新,不然輸出不了文字

}

}catch(FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}finally{

try{

inputStreamReader.close();

//資源關閉原則,先開後關(前提這些資源有關聯性)

osw.close();

fox.close();

fis.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

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