字符流例子

【例子1】向文件中写入数据

现在我们使用字符流


/**  
 * 字符流  
 * 写入数据  
 */

import java.io.*;

class hello{

    public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); Writer out =new FileWriter(f); String str="hello"; out.write(str); out.close(); } } 

当你打开hello。txt的时候,会看到hello

其实这个例子上之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。

当你如果想问文件中追加内容的时候,可以使用将上面的声明out的哪一行换为:


Writer out =new FileWriter(f,true);

这样,当你运行程序的时候,会发现文件内容变为:


hellohello如果想在文件中换行的话,需要使用“\r\n”

比如将str变为String str="\r\nhello";

这样文件追加的str的内容就会换行了。

【例子2】从文件中读内容:


/**  
 * 字符流   
 * 从文件中读出内容  
 */

import java.io.*;

class hello{

    public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); char[] ch=new char[100]; Reader read=new FileReader(f); int count=read.read(ch); read.close(); System.out.println("读入的长度为:"+count); System.out.println("内容为"+new String(ch,0,count)); } } 

【运行结果】:


读入的长度为:17

内容为hellohello

hello

当然最好采用循环读取的方式,因为我们有时候不知道文件到底有多大。


/**  
 * 字符流   
 * 从文件中读出内容   
 */

import java.io.*;

class hello{

    public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); char[] ch=new char[100]; Reader read=new FileReader(f); int temp=0; int count=0; while((temp=read.read())!=(-1)){ ch[count++]=(char)temp; } read.close(); System.out.println("内容为"+new String(ch,0,count)); } } 

【运行结果】:


内容为hellohello

hello

转载于:https://www.cnblogs.com/yuyu666/p/9733900.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值