您的位置:首页 > 编程语言 > Java开发

java IO总结之字符流操作文件读写

2014-07-01 18:03 886 查看
package com.java;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class IOTest5 {

	/**
	 * 字符流操作文件读写
	 */
	public static void main(String[] args) {
		FileReader fr = null;
		FileWriter fw = null;
		try {
			fr = new FileReader("from.txt");
			fw = new FileWriter("to.txt");
			// 单个字符的循环输入输出
			oneWordIO(fr, fw);
			// 一行一行循环输入输出
			oneLineIO(fr, fw);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fw.close();
				fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 一行一行循环输入输出
	 */
	private static void oneLineIO(FileReader in, FileWriter out)
			throws IOException {
		char[] buf = new char[1024];
		int len = -1;
		while ((len = in.read(buf)) != -1) {
			out.write(buf, 0, len);
			out.flush();
		}
	}

	/**
	 * 单个字符的输入整行输出
	 */
	private static void oneWordIO(FileReader in, FileWriter out)
			throws IOException {
		int ch = -1;
		while ((ch = in.read()) != -1) {
			out.write(ch);
			out.flush();
		}
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: