zoukankan      html  css  js  c++  java
  • 161012、JAVA读写文件,如何避免中文乱码

    1、JAVA读取文件,避免中文乱码。
    
    /**
      * 读取文件内容
      * 
      * @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、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);
       writer.write(fileContent +  "
    ");
       writer.close();
      } catch (Exception e) {
       System.out.println("写文件内容操作出错");
       e.printStackTrace();
      }
    }
  • 相关阅读:
    redis实现与分析
    NULL, '',0 '0'的区别
    Linux strace命令
    strcpy和memcpy的区别
    图书推荐
    php与mysql通讯那点事
    linux命令汇总
    linux系统信息查询及相关概念
    LNMP zabbix安装
    lftp查看文件时间与登录服务查看文件时间相差8小时
  • 原文地址:https://www.cnblogs.com/zrbfree/p/5972632.html
Copyright © 2011-2022 走看看