FileWriter cannot write UTF-8. I believe many new users have met FileWriter. let's solve this problem today. Let's look at the example below.
Package cn. yethyeth. sample. io;
Import java. io. FileNotFoundException;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. OutputStreamWriter;
Import java. io. UnsupportedEncodingException;
/***//**
* 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.
*
* See:
* Http://www.malcolmhardie.com/weblogs/angus/2004/10/23/java-filewriter-xml-and-utf-8/
*/
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 ();
}
}
}