使用输入输出IO流以及缓冲流实现文本文件复制的五种方法

时间:2021-05-14 21:02:01

IO流以及缓冲流可以帮我们实现文本文件的读写操作, 关于它们的使用可以去参考这篇博客io流/缓冲流.

接下来我们直接来看复制文本文件的五种方法,直接看代码:

package com.qibao.iostream;

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

public class FileCopyDemo {

	public static void main(String[] args) throws IOException {

		String srcFileName = "src\\com\\qibao\\iostream\\FileCopyDemo.java";
		String destFileName = "src\\com\\qibao\\iostream\\Copy.txt";
		method1(srcFileName, destFileName);
		method2(srcFileName, destFileName);
		method3(srcFileName, destFileName);
		method4(srcFileName, destFileName);
		method5(srcFileName, destFileName);
	}

	/*
	 * 基本IO流一次读写一个字符
	 */
	private static void method1(String srcFileName, String destFileName) throws IOException {
		// 创建输入流对象
		FileReader fr = new FileReader(srcFileName);
		// 创建输出流对象
		FileWriter fw = new FileWriter(destFileName);

		int ch;
		// 一次读写一个字符
		while ((ch = fr.read()) != -1) {
			fw.write(ch);
			fw.flush();
		}

		// 释放资源
		fw.close();
		fr.close();
	}

	/*
	 * 基本IO流一次读取一个数组
	 */
	private static void method2(String srcFileName, String destFileName) throws IOException {
		// 创建输入流对象
		FileReader fr = new FileReader(srcFileName);
		// 创建输出流对象
		FileWriter fw = new FileWriter(destFileName);

		char[] chs = new char[1024];
		int len;
		// 一次读写一个字符数组
		while ((len = fr.read(chs)) != -1) {
			fw.write(chs, 0, len);
			fw.flush();
		}

		// 释放资源
		fw.close();
		fr.close();
	}

	/*
	 * 缓冲流一次读写一个字符
	 */
	private static void method3(String srcFileName, String destFileName) throws IOException {
		// 创建输入缓冲流对象
		BufferedReader br = new BufferedReader(new FileReader(srcFileName));
		// 创建输出缓冲流对象
		BufferedWriter bw = new BufferedWriter(new FileWriter(destFileName));

		int ch;
		// 缓冲流一次读写一个字符
		while ((ch = br.read()) != -1) {
			bw.write(ch);
			bw.flush();
		}

		// 释放资源
		bw.close();
		br.close();
	}

	/*
	 * 缓冲流一次读取一个数组
	 */
	private static void method4(String srcFileName, String destFileName) throws IOException {
		// 创建输入缓冲流对象
		BufferedReader br = new BufferedReader(new FileReader(srcFileName));
		// 创建输出缓冲流对象
		BufferedWriter bw = new BufferedWriter(new FileWriter(destFileName));

		char[] chs = new char[1024];
		int len;
		// 一次读写一个字符数组
		while ((len = br.read(chs)) != -1) {
			bw.write(chs, 0, len);
			bw.flush();
		}

		// 释放资源
		bw.close();
		br.close();

	}

	/*
	 * 缓冲流一次读取字符串
	 */
	private static void method5(String srcFileName, String destFileName) throws IOException {
		// 创建输入缓冲流对象
		BufferedReader br = new BufferedReader(new FileReader(srcFileName));
		// 创建输出缓冲流对象
		BufferedWriter bw = new BufferedWriter(new FileWriter(destFileName));

		// 缓冲流一次读取一行数据
		String str;
		while ((str = br.readLine()) != null) {
			bw.write(str);
			bw.newLine();
			bw.flush();
		}

		// 释放资源
		bw.close();
		br.close();
	}

}