When I output application error logs today, I use the following statement to output Chinese characters with garbled characters:
[Java]
File file = new File (ERRORLOG_PATH_SDCARD_DIR, needWriteFiel
+ ERRORLOG_FILEName );
Try {
If (! File. exists ()){
File. createNewFile ();
}
FileWriter filerWriter = new FileWriter (file, true); // append
BufferedWriter bufWriter = new BufferedWriter (filerWriter );
BufWriter. write (errorMsg. toString ());
BufWriter. newLine ();
BufWriter. close ();
FilerWriter. close ();
} Catch (IOException e ){
Log. d (TAG, "Recording local Log exceptions", e );
}
You can use OutputStreamWriter filerWriter = new OutputStreamWriter (new FileOutputStream (file, true), "GBK"); To solve the garbled problem.
[Java]
File file = new File (ERRORLOG_PATH_SDCARD_DIR, needWriteFiel
+ ERRORLOG_FILEName );
Try {
If (! File. exists ()){
File. createNewFile ();
}
// Set the output encoding to solve Chinese garbled characters
OutputStreamWriter filerWriter = new OutputStreamWriter (new FileOutputStream (file, true), "GBK ");
// FileWriter filerWriter = new FileWriter (file, true); // append
BufferedWriter bufWriter = new BufferedWriter (filerWriter );
BufWriter. write (errorMsg. toString ());
BufWriter. newLine ();
BufWriter. close ();
FilerWriter. close ();
} Catch (IOException e ){
Log. d (TAG, "Recording local Log exceptions", e );
}
Explanation:
* The file name is FileWriterSubstituteSample, which is actually a replacement for FileWriter.
* When FileWriter writes a file, the encoding method seems to be System. encoding or System. file. encoding,
* In the Chinese win encoding is basically gb2312, In the win en is basically iso-8859-1, in short not UTF-8.
* Therefore, you cannot use FileWriter to create a UTF-8 file.
* Currently, you do not know how to change the encoding method used to write files. Therefore, you can use the following method to create a UTF-8 file.
[Java]
Public class FileWriterSubstituteSample ...{
Public static void main (String [] args )...{
String path = "cn/yethyeth/sample/resources/XML_UTF-8.xml ";
Try ...{
OutputStreamWriter out = new OutputStreamWriter (
New FileOutputStream (path), "UTF-8 ");
Out. write ("<? Xml version = "1.0" encoding = "UTF-8"?> <A> This is a test. </A> ");
Out. flush ();
Out. close ();
System. out. println ("success ...");
} Catch (UnsupportedEncodingException e )...{
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (FileNotFoundException e )...{
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (IOException e )...{
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}