IO流之FileWirter和FileReader

来源:互联网 发布:javascript 进度条 编辑:程序博客网 时间:2024/06/14 00:54

 

一.FileWriter(文件输出字符流)

     FileWriter与FileOutputStream类似,不过FileWriter是字符流,而FileOutputStream是字节流。

构造方法:

1.public File(FIle file)throws IOException------根据File创建FileWriter实例

2.public File(File file,boolean append)throws IOException--------根据File创建FileWriter实例,当append为true 时追加内容到原内容后面

 

使用示例:

Java代码  收藏代码
  1. public static void main(String[] args) {    
  2.        File  file=new File("L:\\test.txt");  
  3.        
  4.        try {  
  5.         //创建一个字符输出流对象,true表示内容追加  
  6.         Writer wr=new FileWriter(file,true);  
  7.           
  8.         String info="好好学习,天天向上";  
  9.         //向文件中输出  
  10.         wr.write(info);  
  11.         //关闭流  
  12.         wr.close();  
  13.     } catch (IOException e) {  
  14.         e.printStackTrace();  
  15.     }  

 

一.FileReader(文件输入字符流)

      FileReader与FileInputStream类似,不过FileReader是字符流,而FileInputStream是字节流。

 

具体示例:

Java代码  收藏代码
  1. public static void main(String[] args) {    
  2.        File  file=new File("L:\\test.txt");  
  3.        
  4.        try {  
  5.         //创建一个字符输入流对象  
  6.         Reader in=new FileReader(file);  
  7.         //设置指定长度字符数组读取  
  8.         char []cs=new char[7];  
  9.         StringBuffer sb=new StringBuffer();  
  10.         int len=-1;  
  11.         //读取文件  
  12.         while((len=in.read(cs))!=-1)  
  13.         {  
  14.             sb.append(new String(cs,0,len));  
  15.               
  16.         }  
  17.         System.out.println("文件内容为: "+sb);  
  18.         //关闭流  
  19.         in.close();  
  20.     } catch (IOException e) {  
  21.         e.printStackTrace();  
  22.     }  
  23.      
  24.     }    

 运行结果:



 

 

此时我们把换成用字节输入流FileInputStream来读取,如下:

Java代码  收藏代码
  1.   public static void main(String[] args) {    
  2.      File  file=new File("L:\\test.txt");  
  3.      
  4.      try {  
  5.     //创建一个字节输入流对象  
  6. InputStream in=new FileInputStream(file);  
  7. //设置指定长度字节数组读取  
  8. byte []bytes=new byte[7];  
  9. StringBuffer sb=new StringBuffer();  
  10. int len=-1;  
  11. //读取文件  
  12. while((len=in.read(bytes))!=-1)  
  13. {  
  14.     sb.append(new String(bytes,0,len));  
  15.       
  16. }  
  17. System.out.println("文件内容为: "+sb);  
  18. //关闭流  
  19. in.close();  
  20.  catch (IOException e) {  
  21. e.printStackTrace();  
  22.   
  23.    
  24.   }    

 

此时的运行结果出现乱码:

 



 

不禁会想,第一种字符读取没有出现乱码,而使用字节读取就出现了乱码。

  其实FileReader是在FileInputStream的基础上实现的,看FileReader源码可知。


 

    字符流是按一个个字符为单位来读取,字节流是按一个个字节为单位来读取。所以我们就可以理解为什么字节流读取汉字有时会出现乱码的原因了。在这里是因为我们每次读取7个字节,而一个汉字可能是2个或3个字节组成,要看使用的编码。当我们取了7个字节后使用new String(bytes,0,len)转化为字符串,可能我们获得了一个汉字的不完整字节导致产生乱码。然后我们字节读取是最基础的,是正确的,任何基于字节的操作都是正确的,当我们需要读取的文本有汉字时建议使用字符输入流FileReader防止产生乱码。

0 0