FileWriter不能写utf-8的原因及解决

本文介绍了一个使用Java编程语言实现的示例,展示了如何通过OutputStreamWriter类以UTF-8编码方式写入文件,以解决FileWriter不支持直接指定编码的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * Copyright 2007 nuaa. All rights reserved.
 * This file is by yethyeth, 2007-9-3 9:27:34.
 
*/
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;

// TODO: Auto-generated Javadoc
/**
 *//**
 * 本文件名为FileWriterSubstituteSample,实际上是在寻找FileWriter的替代者。
 * 因为FileWriter在写文件的时候,其编码方式似乎是System.encoding或者System.file.encoding(已经证明FileWriter和FileReader确实使用系统当前默认的编码方式,更多信息包括FileReader的详见http://www.javapractices.com/Topic42.cjp),
 * 在中文win下encoding基本是gb2312,在en的win下基本是iso-8859-1,总之不是utf-8。
 * 所以要创建一个utf-8的文件,用FileWriter是不行的。(FileWriter和FileReader都不支持通过参数指定编码方式,而OutputStreamWriter和InputStreamReader可以。这两个类从名字上就可以看到是字节流和字符流的组合,实际上也是连接两者的桥梁)。 目前不知道如何更改其用来写文件的编码方式,因此对于创建utf-8文件使用如下方式来代替。
 * 
 * 参见:
 * 
http://www.malcolmhardie.com/weblogs/angus/2004/10/23/java-filewriter-xml-and-utf-8/
 
*/
public class FileWriterSubstituteSample {
    
    
/**
     * The main method.
     * 
     * 
@param args
     *            the arguments
     
*/
    
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();
        }
    }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值