在創建文件並打印字符串時,如果不指定編碼,默認是按系統的編碼格式來。比如我們的linux環境中編碼如下:
CMREAD-SV43 /home/wlf> locale LANG=en_US.UTF-8 LC_CTYPE="zh_CN.GBK" LC_NUMERIC="zh_CN.GBK" LC_TIME="zh_CN.GBK" LC_COLLATE="zh_CN.GBK" LC_MONETARY="zh_CN.GBK" LC_MESSAGES="zh_CN.GBK" LC_PAPER="zh_CN.GBK" LC_NAME="zh_CN.GBK" LC_ADDRESS="zh_CN.GBK" LC_TELEPHONE="zh_CN.GBK" LC_MEASUREMENT="zh_CN.GBK" LC_IDENTIFICATION="zh_CN.GBK" LC_ALL=zh_CN.GBK
中文編碼看LC_ALL,這里我們環境配置的是GBK,那么如下代碼就是使用GBK來的,因為這里並未設置默認編碼格式:
protected void writerLog(String content) { // 記錄創建時間為當前時間 createDate = new Date(); try { // 生成文件對象,如果文件不存在,要創建新文件。 File file = new File(this.fileName); if (!file.exists() && file.createNewFile()) { // 上面方法有返回值,findBugs會報警,所以采用空實現的形式解決 ; } // 獲得當前文件大小 this.fileSize = file.length(); file = null; // 打開輸出 this.logWriter = new PrintWriter(new FileWriter(this.fileName, true), true); } catch (IOException e) { e.printStackTrace(); this.logWriter = null; } this.logWriter.print(content); this.logWriter.flush(); }
如何指定具體的編碼格式呢?我們把這一行改下:
this.logWriter = new PrintWriter(new FileWriter(this.fileName, true), true);
使用OutputStreamWriter對象來指定UTF-8編碼:
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(this.fileName, true), "UTF-8"); this.logWriter = new PrintWriter(osw, true);