Solutions that do not write UTF-8 using Java filewriter

Source: Internet
Author: User

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 ();
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.