關於JAVA IO流寫檔案數字亂碼的問題
在完成JavaWeb作業時遇到一題是需要持久化儲存登入人數的,題主當時就在Listener裡寫了輸入輸出兩個函式,但是檢查一看發現寫入的數字變成了亂碼(其實不能說是亂碼)。
當時很疑惑就改用瞭如下程式碼:
寫程式碼:
File file = new File(PATH);
if(file.exists()==false)
{
file.createNewFile();
}
//設定編碼
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file,false),"UTF-8");
BufferedWriter writer = new BufferedWriter(out);
writer.write(5);
writer.close();
讀程式碼:
File file = new File(PATH);
if(file.exists()==false)
{
file.createNewFile();
}
//設定編碼
InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader reader = new BufferedReader(in);
String msg = reader.readLine();
if(msg!=null)
{
if((msg.equals("")==false)||isNumeric(msg)==true)
{
count = Integer.valueOf(msg);
}
}
reader.close();
然並卵,還是不顯示數字。
好吧,最後終於發現真相了:
其實outsteam.write()裡面是一個單獨的數字時,是把數字轉換為ASCII碼傳進去的,所以也並不是什麼亂碼。
write()API如下:
Writes a single character.
- Parameters:
- c int specifying a character to be written//關鍵
- Throws:
- IOException - If an I/O error occurs
解決方法也很簡單隻需要在數字後面加上 +“” 就好,write就轉換為寫String的方法了
Writes a string.
- Parameters:
- str String to be written
- Throws:
- IOException - If an I/O error occurs