首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java io输出的编码有关问题

2012-11-23 
java io输出的编码问题今天在做应用错误日志输出时,使用以下的写法,输出中文时乱码File file new File(E

java io输出的编码问题

今天在做应用错误日志输出时,使用以下的写法,输出中文时乱码

File file = new File(ERRORLOG_PATH_SDCARD_DIR, needWriteFiel+ ERRORLOG_FILEName);try {if(!file.exists()){file.createNewFile();}FileWriter filerWriter = new FileWriter(file, true); // 追加BufferedWriter bufWriter = new BufferedWriter(filerWriter);bufWriter.write(errorMsg.toString());bufWriter.newLine();bufWriter.close();filerWriter.close();} catch (IOException e) {Log.d(TAG, "记录本地日志异常",e);}


后面查了些资料,可以使用OutputStreamWriter filerWriter = new OutputStreamWriter(new FileOutputStream(file,true),"GBK"); 来解决乱码问题

 

File file = new File(ERRORLOG_PATH_SDCARD_DIR, needWriteFiel+ ERRORLOG_FILEName);try {if(!file.exists()){file.createNewFile();}//设置输出编码,解决中文乱码OutputStreamWriter filerWriter = new OutputStreamWriter(new FileOutputStream(file,true),"GBK");//FileWriter filerWriter = new FileWriter(file, true); // 追加BufferedWriter bufWriter = new BufferedWriter(filerWriter);bufWriter.write(errorMsg.toString());bufWriter.newLine();bufWriter.close();filerWriter.close();} catch (IOException e) {Log.d(TAG, "记录本地日志异常",e);}


解释:

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


 

热点排行