package com.io.buffered; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import ja ...
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 + "\n");//讀取文件換行
}
} 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();
}
}
}
}
}