早晨起來看了看流的概念,又搞出亂碼了-.-! 最後解決了。

Talk is cheap , show me the cood . 不多說,看代碼。



import java.io.*;

/**
* 此測試程序用來理解字節輸入流與輸出流,
* 要保證不亂碼,只要編碼與解碼一致即可!
* 由於我的測試源文件使用UTF-8 編碼 , 讀進內存裏 ===> 字節流 ===> 如果我直接new String(bytes)會以默認編碼
* ===>如果我指定new String(bytes,"UTF-8") 則會編碼與解碼一致,不會亂碼!
*/
public class FileDemo{


public static void main(String args[]){
//1 創建指定輸入流,即源數據
File file = new File("D:\\a.txt");
//2 創建指定輸出流,目的
File file2 = new File("D:\\b.txt");
//3 存放字符串
StringBuilder sb = new StringBuilder();
try{
//創建輸出文件   
file2.createNewFile();
FileInputStream fis = new FileInputStream(file);
OutputStream fos = new FileOutputStream(file2);
byte[] bytes = new byte[1024];
int len = -1;
while((len=fis.read(bytes))!=-1){
//無論源文件a.txt 是什麼編碼,這裏都不會亂碼,只要txt文本編輯程序打開b.txt時使用正確編碼即可。
fos.write(bytes,0,len);
//重點在這裏:如果只是new String(bytes); 的話 在控制檯輸出會亂碼,會以操作系統默認編碼
//如果a.txt 文件中的編碼是UTF-8  這裏就不會亂碼!  如果是其它 仍然亂碼


sb.append(new String(bytes,"UTF-8"));
}
}
catch(Exception ex){
System.out.println(ex);
}
System.out.println(sb);
}


}
發佈了26 篇原創文章 · 獲贊 3 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章