关于javaIO流与字符集的问题总结

      这两天用java写了一个小的脚本,以方便工作使用。但是面对中文字符时总是出现乱码问题。以下是我处理程序的片段代码:

      BufferedWriter bw=null;
    try {
   //创建目录
   File fileDir=new File(cp.getCsv_path());
   if(!fileDir.exists()){
    if(fileDir.mkdirs()){
     //创建文件
     File csvfile=new File(csvpath);
     if(!csvfile.exists()){
      if(!csvfile.createNewFile()){
       System.out.println("create csvfile error");
      }else{
       System.out.println("create csvfile successful!!");
      }
     }
     System.out.println("create csvfileDir ok");
    }else{
     System.out.println("create csvfileDir error");
    }
   }
   bw=new BufferedWriter(new FileWriter(csvpath));
   result=co.getCVSStr()+"\n"+result;
   System.out.println("=========================================");
   System.out.println(result);

  //result.getBytes("UTF-8")将系统默认的字符集转换成UTF-8
   String utfStr=new String(result.getBytes("UTF-8"),"utf-8");

 //在javaIO流写入文件时仍旧使用系统默认的字符集写入文件。 
   bw.write(utfStr);
   bw.flush();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   try {
    bw.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

 

在代码中本以为使用红色区域的代码就可以保证写入文件的字符问UTF-8字符集的。但实际上还是采用操作系统默认的字符集写入文件。其主要的原因,是我没有对IO流进行字符集的指定,所以在流将信息写入文件的时候仍然采用的系统默认的字符集。在代码中红色区域的代码实际上是做了无用功。并没有起到真正的效果。

 

2 .采用以下方式就可以了:

 PrintWriter pw=null;
  try {
   //创建目录
   File fileDir=new File(cp.getCsv_path());
   if(!fileDir.exists()){
    if(fileDir.mkdirs()){
     //创建文件
     File csvfile=new File(csvpath);
     if(!csvfile.exists()){
      if(!csvfile.createNewFile()){
       System.out.println("create csvfile error");
      }else{
       System.out.println("create csvfile successful!!");
      }
     }
     System.out.println("create csvfileDir ok");
    }else{
     System.out.println("create csvfileDir error");
    }
   }
   pw=new PrintWriter(csvpath,"utf-8");
   result=co.getCVSStr()+"\n"+result;
   System.out.println("=========================================");
   System.out.println(result);
   pw.write(result);
   pw.flush();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   pw.close();
  }
  return result;
 }

 

使用PringWriter类在写入文件时使信息解码为字符集为UTF-8格式。具有这样功能类还有OutputStreamWriter和InputStreamWriter。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值