缓冲流---为字节流和字符流复制文件增加缓冲流

时间:2022-07-22
本文章向大家介绍缓冲流---为字节流和字符流复制文件增加缓冲流,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

缓冲流——增强性能

字节流的缓冲流(均未增加新方法)

BufferedInputStream

BufferedOutputStream

字节符的缓冲流

方法名称

方法作用

readLine()

返回值为String对象,读取一行

newLine()

换行符

字节流的缓冲流代码

package cn.hxh.io.buffered;

import java.io.*;

public class BufferedByte {

	public static void main(String[] args) throws IOException {
		CopyFile("D:/aa/a.txt", "D:/aa/b.txt");
	}

	public static void CopyFile(String srcPath, String destPath) throws IOException {
		CopyFile(new File(srcPath), new File(destPath));
	}

	public static void CopyFile(File src, File dest) throws IOException {
		if (src.isDirectory()) {
			throw new IOException("这是一个文件夹");
		}
		InputStream iStream = new BufferedInputStream(new FileInputStream(src));
		OutputStream oStream = new BufferedOutputStream(new FileOutputStream(dest));
		byte[] flush = new byte[1024];
		int len = 0;
		while (-1 != (len = iStream.read(flush))) {
			oStream.write(flush, 0, len);
		}
		oStream.flush();
		oStream.close();
		iStream.close();
	}

}

字符流的缓冲流代码

package cn.hxh.io.buffered;

import java.io.*;

public class BufferedChar {
	public static void main(String[] args) {
		File in = new File("D:/aa/a.txt");
		File out = new File("D:/aa/b.txt");
		BufferedReader re = null;
		BufferedWriter wr = null;
		String line = null;
		try {
			re = new BufferedReader(new FileReader(in));
			wr = new BufferedWriter(new FileWriter(out));
			while (null != (line = re.readLine())) {
				wr.write(line);
				wr.newLine();
			}
			wr.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

			try {
				if (wr != null)
					wr.close();
				if (re != null)
					re.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}
}