读UTF-8 编码的文本

 

FileReader FileWriter 和InputStreamReader OutputStreamWriter 读UTF-8 编码的文本

 

FileReader 和FileWriter 分别是InputStreamReader 和OutputStreamWriter 的直接子类,InputStreamReader 和OutputStreamWriter是字符流通字节流的桥梁,可以显示的指定字符编码,转码是发生在字节流和字符流的临界处的;

而FileReader 和FileWriter 是处理字符文件的便捷类,使用的是默认的字符编码。

 

读UTF-8 字符编码的文件

1 、使用FileReader 类

public static String readUsingFileReader(String fileName,

String encoding) throws IOException{

         StringBuffer sb = new StringBuffer();

         BufferedReader in = new BufferedReader(

                   new FileReader(fileName));

         String s ;

         while ((s=in.readLine())!= null ){

              s = new String((s+ "\n" ).getBytes(),encoding);

              sb.append(s);

         }

         in.close();

         return sb.toString();

     }

 

2 、使用InputStreamReader 类

public static String readUsingInputStreamReader(String fileName,String encoding)

throws IOException{

         StringBuffer sb = new StringBuffer();

         BufferedReader in = new BufferedReader(

                   new InputStreamReader( new FileInputStream(fileName),encoding));

         String s ;

         while ((s=in.readLine())!= null ){

              sb.append(s);

              sb.append( "\n" );

         }

         in.close();

         return sb.toString();

     }

  

使用 FileReader 类我们需要通过 new String((s+ "\n" ).getBytes(),encoding) 进行转码,但还是会出现一些汉字无法解析出来。使用 InputStreamReader 类时我们指定好编码方式能很好的解析。

 

写文件和读文件差不多。

1 、使用FileWriter 类

public static void writeUsingFileWriter(String fileName,String text,

              String encoding) throws IOException{

         PrintWriter out = new PrintWriter(

                   new FileWriter(fileName));

         text = new String(text.getBytes(encoding));

         out.print(text);

         out.close();

     }

 

2 、使用OutputStreamWriter 类

     

public static void writeUsingOutputStreamWriter(String

fileName,String text,String encoding) throws IOException{

         PrintWriter out = new PrintWriter(

new OutputStreamWriter(

new FileOutputStream(fileName),encoding));

         out.print(text);

         out.close();

     }

  

 

 

FileOutputStream /FileInputStream 用于写入诸如图像数据之类的原始字节的流。要写入字符流,考虑使用 FileWriter/FileReader

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值