【IO流之FileWirter和FileReader】

本篇博客主要介绍java的 字符流FileWirter和FileReader流,主要用于操作文件内容。


一.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 时追加内容到原内容后面

使用示例:

  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是字节流。


具体示例:

  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.     }   

复制代码

运行结果:
132516xq1kq0qlbts1r7so.png 
此时我们把换成用字节输入流FileInputStream来读取,如下:

  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.   }   

复制代码

此时的运行结果出现乱码: 132543h3j8mhj9zbb93w1j.png 

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

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


132610ndhqoq4l5oydcncd.png


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


你可能感兴趣的:(java,结构图)