JAVA read and write files from Chinese garbled

1, JAVA read the file, to avoid Chinese garbled.


/ **
  * reads the contents of the file
  * 
  * @param filePathAndName
  * String such as c: \\ 1.txt absolute path
  * @return Boolean
  * /
public static readFile String (String filePathAndName) {
  String fileContent = "";
  the try {  
   File F File new new = (filePathAndName);
   IF (f.isFile () && f.exists ()) {
    the InputStreamReader Read the InputStreamReader new new = (new new the FileInputStream (F), "UTF-. 8");
    the BufferedReader Reader the BufferedReader new new = (Read);
    String Line;
    the while (! (= reader.readLine Line ()) = null) {
     fileContent += line;
    }   
    read.close();
   }
  } catch (Exception e) {
   System.out.println("读取文件内容操作出错");
   e.printStackTrace();
  }
  return fileContent;
}


2、JAVA写入文件,避免中文乱码。


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

}



Note: Transfer from: http: //zhidao.baidu.com/link url = _WJYcFO4l5MqTsCcVB9iKbyH40wKxkYOuDztUPnGE4VTJC88zk-jYojZtWQh90EbKTall_kGCj8K0LKFW8xtuu4aN12NuMVtjJEi6SL8T4G?

Reproduced in: https: //my.oschina.net/u/2552902/blog/543844

Guess you like

Origin blog.csdn.net/weixin_34402408/article/details/92326756