android 文字檔案的正確寫入(防止中文亂碼)
阿新 • • 發佈:2019-02-18
android文字檔案寫入流程
1,寫入檔案的路徑
2,獲取寫入流
3,寫入資料,記得轉換格式(UFT-8在android不能用,只能用gbk)
開始寫程式碼:
首先根據檔案地址判斷檔案是否存在,不存在就建立新檔案
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
然後獲取寫入流
FileOutputStream outputStream = new FileOutputStream(file, true);
true是不覆蓋寫入檔案,只在文字最後寫入,false是隻在文字最開始寫入,只傳入file則覆蓋式寫入文字檔案。
最後寫入內容
//記住用gbk
outputStream.write(content.getBytes("gbk"));
當然不要忘了關閉
outputStream.flush();
outputStream.close();
還有捕獲異常
FileNotFoundException和IOException
完成。。。
總體程式碼:
public static void writeStr2Txt(String content, String
path) {
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(file, true);
outputStream.write(content.getBytes("gbk"));
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}