Java IO读取文件中文乱码问题 (读写文件不错的通用写法)

时间:2023-01-11 15:43:45

来自:http://java.chinaitlab.com/advance/819754.html

1、JAVA读取文件,避免中文乱码。

  /**

  * 读取文件内容

  *

  * @param filePathAndName   String  读取文件路径

  * @return String  文件中的内容

  */

  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、JAVA写入文件,避免中文乱码。

  /**

  * 写文件

  *

  * @param filePathAndName   String  写文件路径

  * @param fileContent   String  需要写入的内容

  */

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

  }

  }