FileWriter can not write utf-8, I believe that many novice have encountered it, today we will solve this problem, look at the following example.
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;
/** *//**
* This article, called Filewritersubstitutesample, is actually looking for a replacement for FileWriter.
* Because FileWriter seems to encode system.encoding or System.file.encoding when writing files,
* encoding is basically gb2312 under Chinese win, In EN's win under the basic is iso-8859-1, in short is not utf-8.
* So to create a utf-8 file, it's not possible to use FileWriter.
* Currently does not know how to change the encoding used to write the file, so you can replace it with the following method for creating the 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 the 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 ();
}
}