IO流之FileWirter和FileReader

         本篇博客主要介绍字符流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 时追加内容到原内容后面

 

使用示例:

public static void main(String[] args) {  
       File  file=new File("L:\\test.txt");
     
       try {
    	//创建一个字符输出流对象,true表示内容追加
		Writer wr=new FileWriter(file,true);
		
		String info="好好学习,天天向上";
		//向文件中输出
		wr.write(info);
		//关闭流
		wr.close();
	} catch (IOException e) {
		e.printStackTrace();
	}

 

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

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

 

具体示例:

public static void main(String[] args) {  
       File  file=new File("L:\\test.txt");
     
       try {
    	//创建一个字符输入流对象
		Reader in=new FileReader(file);
		//设置指定长度字符数组读取
		char []cs=new char[7];
		StringBuffer sb=new StringBuffer();
		int len=-1;
		//读取文件
		while((len=in.read(cs))!=-1)
		{
			sb.append(new String(cs,0,len));
			
		}
		System.out.println("文件内容为: "+sb);
		//关闭流
		in.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
   
    }  

 运行结果:



 

 

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

    public static void main(String[] args) {  
       File  file=new File("L:\\test.txt");
     
       try {
    	//创建一个字节输入流对象
		InputStream in=new FileInputStream(file);
		//设置指定长度字节数组读取
		byte []bytes=new byte[7];
		StringBuffer sb=new StringBuffer();
		int len=-1;
		//读取文件
		while((len=in.read(bytes))!=-1)
		{
			sb.append(new String(bytes,0,len));
			
		}
		System.out.println("文件内容为: "+sb);
		//关闭流
		in.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
   
    }  

 

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

 



 

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

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


 

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

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值