面向字符的输入输出流

一:面向符的输入流


父类Reader为抽象类,不能被实例化。面向字符的输入流都是Reader类的子类,其类层次结构下图所示:



下表 列出了 Reader 的主要子类及说明


下表 列出了 Reader常用方法:


二:面向字符的输出流



父类Writer为抽象类,不能被实例化。面向字符的输入流都是Writer类的子类,其类层次结构下图所示:


下表 列出了 Writer 的主要子类及说明


下表 列出了 Writer常用方法:


三:面向字符的输入输出流简单应用

1:通过字符向file中写数据

	public void WriterFileByChar(File file) {
		FileWriter fw = null;
		char[] chars = new char[128];
		int len = chars.length;
		for (int i = 0; i < len; i++) {
			chars[i] = (char) i;
		}
		try {
			fw = new FileWriter(file);
			fw.write(chars);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fw != null)
					fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
2: 通过字符从file中读取数据
	public void ReaderFileByChar(File file) {
		FileReader fr = null;
		try {
			fr = new FileReader(file);
			int c;
			while ((c = fr.read()) != -1) {
				System.out.print(c);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fr != null)
					fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
3: 通过字符从file1将数据复制到file2

	/**
	 * 文件复制操作
	 * 
	 */
	public void Coppy(File file1,File file2) {
		FileReader fil = null;
		FileWriter fos = null;
		try {//捕获异常
			fil = new FileReader(file1);//实例化输入流
			fos = new FileWriter (file2);//实例化输出流
			int temp;
			//从file1中通过输入流调用fil.read()读取数据,返回值为-1时表示数据读完了
			while ((temp = fil.read()) != -1) {
				fos.write((char) temp);//将数据写入file2
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fil != null) {
					fil.close();//关闭输入流
				}
				if (fos != null) {
					fos.close();//关闭输出流
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}



  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值