您的位置:首页 > 编程语言 > Java开发

java io的编码问题

2010-06-27 18:22 197 查看
1。http://blog.csdn.net/qingyuexiao/archive/2009/04/21/4097723.aspx





1、J***A读取文件,避免中文乱码。

/**
* 读取文件内容
*
* @param filePathAndName
* String 如 c://1.txt 绝对路径
* @return boolean
*/
public static String readFile(String filePathAndName) {
String fileContent = "";
try {
File f = new File(filePathAndName);
if(f.isFile()&&f.exists()){
InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8");
BufferedReader reader=new BufferedReader(read);
String line;
while ((line = reader.readLine()) != null) {
fileContent += line;
}
read.close();
}
} catch (Exception e) {
System.out.println("读取文件内容操作出错");
e.printStackTrace();
}
return fileContent;
}

2、J***A写入文件,避免中文乱码。

public static void writeFile(String filePathAndName, String fileContent) {
try {
File f = new File(filePathAndName);
if (!f.exists()) {
f.createNewFile();
}
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");
BufferedWriter writer=new BufferedWriter(write);
//PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));
//PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));
writer.write(fileContent);
writer.close();
} catch (Exception e) {
System.out.println("写文件内容操作出错");
e.printStackTrace();
}
}

2.http://tech.ddvip.com/2007-10/119238610036399.html

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();
    }
  }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: