首页 > 开发 > JSP > 正文

使用FileWriter可以写UTF-8的解决方法

2020-05-06 19:53:36
字体:
来源:转载
供稿:网友

FileWriter不能写utf-8,相信好呢多新手都遇到过吧,今天我们就来解决这个问题,看下面的例子。

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;
/** *//**
* 本文件名为FileWriterSubstituteSample,实际上是在寻找FileWriter的替代者。
* 因为FileWriter在写文件的时候,其编码方式似乎是System.encoding或者System.file.encoding,
* 在中文win下encoding基本是gb2312,在en的win下基本是iso-8859-1,总之不是utf-8。
* 所以要创建一个utf-8的文件,用FileWriter是不行的。
* 目前不知道如何更改其用来写文件的编码方式,因此对于创建utf-8文件使用如下方式来代替。
*
* 参见:
* 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>这是测试。</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();
}
}
}

设计家园 整理

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表