java使用字符流写入和读取文件内容

首先了解一下什么是字符流和字节流

字节流:
操作的是byte类型的数据,以byte为准,主要有两大抽象类OutputStreamInputStream,使用这两个抽象类必须用其对应的子类FileOutputStreamFileInputStream
字节流的示例
字符流:
输入和输出操作的是字符,写入和读取的类是WriterReader,这两个同样也是抽象类,分别对相对应的子类FielWriteFileReader
示例1,使用字符流向文件中写入内容:
列举了三种方式,字符串、字符数组、字符

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class WriterDemo {
	public static void main(String[] args) {
		//指定文件路径
		File file = new File("e:"+File.separator+"a"+File.separator+"test.txt");
		
		Writer w =null;
		StringBuffer buf = new StringBuffer();
		for(int i=0;i<1;i++) {
			buf.append("没错,就是我");
		}
		String str = new String(buf); //将StringBuffer字符转化成String字符串
		char[] ch = new char[] {'a','b','c'};//直接使用char字符
		/* 注释 部分是使用循环方式但各项文件中写入内容*/
//		char[] ch01 = new char[str.length()];
//		 str.getChars(0, str.length(), ch01, 0);
//		 for(int i=0;i<ch01.length;i++) {
//			 System.out.print(ch01[i]+" ");
//		 }
		//使用字符流,必须关闭程序才会执行,没有关闭前,内容都是存下内存区的缓冲区
		try {
			w = new FileWriter(file,true);
			w.write(str);	//将字符串写入到文件中
			w.write(ch);	//直接将字符数组写入
//			w.write(ch01);//将从字符串转来的字符数组写入文件
			w.close();		//关闭
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
}

实例2:
使用字符流从文件中读取内容:

package Demo0321;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class ReadDemo {
	public static void main(String[] args) {
		//使用File类定位文件
		File file = new File("e:"+File.separator+"a"+File.separator+"test.txt");
		
		Reader r = null;
		char[] ch=new char[(int)file.length()];
		int temp,len=0,i=0;
		try {
			r = new FileReader(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		try {
			//len = r.read(ch);//一次性读取到字符数组
			while((temp=r.read())!=-1) {//每次只能读取一个字符,通过循环的方式放入到字符数组中
				ch[i++] = (char)temp;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			r.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(new String(ch,0,i));
		

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值