字符流

本文深入解析了Java中字符流的基本概念,包括输入流Reader和输出流Writer的使用方法,构造方法,以及各种读写操作。通过实例展示了如何利用字符流进行文件的读取和写入。

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

字符流只能操作于纯文本的数据

一、输入流Reader

构造方法

protected FilterReader(Reader in) 创建一个新的 filtered reader。

Reader read=new FileReader("D:/test.txt");

方法:

  1. abstract void close() 关闭该流并释放与之关联的所有资源。
  2. void mark(int readAheadLimit) 标记流中的当前位置。
  3. int read() 读取单个字符。
  4. int read(char[] cbuf) 将字符读入数组。
  5. abstract int read(char[] cbuf, int off, int len) 将字符读入数组的某一部分。
  6. int read(CharBuffer target) 试图将字符读入指定的字符缓冲区。
  7. boolean ready() 判断是否准备读取此流。
  8. void reset() 重置该流。
  9. long skip(long n) 跳过字符。

步骤

  1. 选择流
  2. 读入
  3. 关闭

实例

public static void main(String[] args) throws Exception {
	//1.选择流
	Reader read=new FileReader("D:/test01.txt");
	//2.读入 写出
	// int num=read.read(); 读取单个字符
	//读取多个字符
	char[] car=new char[1024];
	int len=-1; //存储读取到数组中的数据个数
	while((len=read.read(car))!=-1){
		System.out.println(car);
	}
	//3.关闭
	read.close();
}

三、输出流Writer

构造方法

FileWriter(String fileName) 根据给定的文件名构造一个 FileWriter 对象。

Writer write=new FileWriter("D:/test.txt");

FileWriter(String fileName, boolean append) 根据给定的文件名以及指示是否附加写入数据的 boolean 值来构造 FileWriter 对象。

Writer write=new FileWriter("D:/test.txt",true);

方法:

  1. Writer append(char c) 将指定字符添加到此 writer。
  2. Writer append(CharSequence csq) 将指定字符序列添加到此 writer。
  3. Writer append(CharSequence csq, int start, int end) 将指定字符序列的子序列添加到此 writer.Appendable。
  4. abstract void close() 关闭此流,但要先刷新它。
  5. abstract void flush() 刷新该流的缓冲。
  6. void write(char[] cbuf) 写入字符数组。
  7. abstract void write(char[] cbuf, int off, int len) 写入字符数组的某一部分。
  8. void write(int c) 写入单个字符。
  9. void write(String str) 写入字符串。
  10. void write(String str, int off, int len) 写入字符串的某一部分。

步骤

  1. 建立联系
  2. 创建流
  3. 写出
  4. 刷出
  5. 关闭

实例

public static void main(String[] args) throws IOException {
	//1.选择流
	Reader read=new FileReader("D:/test01.txt");
	Writer write=new FileWriter("D:/test02.txt",true);
	//2.读入 写出
	// int num=read.read(); 读取单个字符
	char[] car=new char[1024];
	int len=-1; //存储读取到数组中的数据个数
	while((len=read.read(car))!=-1){
		write.write(car, 0, len);
	}
	//3.刷出
	write.flush();
	//4.关闭
	write.close();
	read.close();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值