package com.io.buffered;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.Test;
/**
* 使用缓冲流实现文本文件的copy
*
*/
public class BufferedStreamFileText {
@Test
public void copyTestTextTest() {
// 记录耗时
long start = System.currentTimeMillis();
String src = "./hello.txt";
String dest = "./world.txt";
copyTestText(src, dest);
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
}
@SuppressWarnings("resource")
public static void copyTestText(String src, String dest) {
// 3、创建FileWriter
FileWriter fw = null;
// 4、创建BufferedWriter 用于包装节点流,提高效率
BufferedWriter bw = null;
try {
// 1、创建FileReader
FileReader fr = new FileReader(src);
// 2、创建BufferedReader 用于包装节点流,提高效率
BufferedReader br = new BufferedReader(fr);
fw = new FileWriter(dest);
bw = new BufferedWriter(fw);
// 5、读取指定文件内容
String str = null;
while ((str = br.readLine()) != null) {
// 6、将读取的内容写到目标地点
bw.write(str + "
");//读取文件换行
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 7、关闭流
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}