Java字符输入(FileWriter)输出(FIleReader)流

本文详细介绍了Java中FileReader和FileWriter的使用方法,包括如何读取和写入文本文件,展示了单字节读取和使用数组缓冲区提高读取速度的技术,以及FileWriter的构造方法和写入操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方API:

https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html
https://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html

	public static void main(String[] args) throws IOException {
		writerText();
		//readText();
	}
	/**
	 * 读取文本信息继承
	 * 
	 */
	private static void readText() throws IOException {
		//单字节读取
		/*
		FileReader fr = new FileReader("D:\\a.txt");
		int len = 0;
		while((len = fr.read()) != -1){
			System.out.print((char)len);//可以解码ASCLL码表来查看
		}
		fr.close();
		*/
		//使用数组缓冲区可以提高读取速度
		FileReader fr1 = new FileReader("D:\\a.txt");
		char[] c = new char[1024];
		int len1 = 0;
		while((len1 = fr1.read(c)) != -1){
			System.out.print(new String( c, 0, len1));
		}
		fr1.close();
	}
	/**
	 * 专门写文本信息,如果写入文本的文件不存在则构造器会创建一个进行操作
	 * 	类继承关系:
	 * 	Writer -- abstract
	 *     |- OutputStreamWriter -- class
	 *  			|- FileWriter -- class 没有单独方法都继承自父类,但是构造方法使用方便,是父类的扩展
	 */
	private static void writerText() throws IOException {
		FileWriter fw = new FileWriter("D:\\a.txt");//参数也可以使用File,参数(String,boolean),(File,boolean)是否追加写入文本信息,默认false
		fw.write("你好");//写入字符串
		fw.flush(); //写入后就刷新,再关闭流之前先刷新,否则会导致资源浪费
		fw.write("我好大家好", 0, 2);//写入的字符串,起始位置,写入长度
		fw.flush();
		char[] c = {'a','b','c','d','e','f'};
		fw.write(c); //写入char数组
		fw.flush();
		fw.write(100); //写入整数'd'
		fw.flush();
		char[] ch = {'好','汉','绕','命'};
		fw.write( ch, 0, 2); //数组,起始位置,长度
		fw.flush();
		fw.close();
		System.out.println("写入完成");
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值