package unittest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
-
@author Dylaniou
-
读取字符数组的效率显然要比读取字符效率高很多
*/
public class CopyFile {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader(“E:\a\b\copyfrom.txt”);
FileWriter fw = new FileWriter(“E:\a\b\copyto.txt”);FileReader fr1 = new FileReader("E:\\a\\b\\copyfrom1.txt"); FileWriter fw1 = new FileWriter("E:\\a\\b\\copyto1.txt"); FileReader fr2 = new FileReader("E:\\a\\b\\copyfrom2.txt"); FileWriter fw2 = new FileWriter("E:\\a\\b\\copyto2.txt"); FileReader fr3 = new FileReader("E:\\a\\b\\copyfrom3.txt"); FileWriter fw3 = new FileWriter("E:\\a\\b\\copyto3.txt"); method1(fr, fw);//一次读取一个字符 method2(fr1, fw1);//一次读取一个字符数组 method3(fr2, fw2);//缓冲区字符读写 method4(fr3, fw3);//缓冲区字符数组读写 fr.close(); fw.close();
}
/**
- 一次读取一个字符
- @param fr
- @param fw
- @throws IOException
*/
private static void method1(FileReader fr, FileWriter fw) throws IOException {
// TODO Auto-generated method stub
long t1 = System.currentTimeMillis();
int ch;
while((ch = fr.read())!=-1){
fw.write(ch);
}
fw.flush();
long t2 = System.currentTimeMillis();
getTime(“File字符”,t1,t2);
}
/**
- 一次读取一个字符数组
- @param fr
- @param fw
- @throws IOException
*/
private static void method2(FileReader fr, FileWriter fw) throws IOException {
// TODO Auto-generated method stub
long t1 = System.currentTimeMillis();
char[] ch = new char[1024];
int len;
while((len = fr.read(ch))!=-1){
fw.write(ch,0,len);
}
fw.flush();
long t2 = System.currentTimeMillis();
getTime(“File字符数组”,t1,t2);
}
/**
- 缓冲区字符读写
- @param fr
- @param fw
- @throws IOException
*/
private static void method3(FileReader fr, FileWriter fw) throws IOException {
// TODO Auto-generated method stub
long t1 = System.currentTimeMillis();
BufferedReader br = new BufferedReader(fr);
BufferedWriter bw = new BufferedWriter(fw);
int c;
while((c = br.read())!=-1){
bw.write©;
}
bw.flush();
long t2 = System.currentTimeMillis();
getTime(“Buffered字符”,t1,t2);
}
/**
- 缓冲区字符数组读写
- @param fr
- @param fw
- @throws IOException
*/
private static void method4(FileReader fr, FileWriter fw) throws IOException {
// TODO Auto-generated method stub
long t1 = System.currentTimeMillis();
BufferedReader br = new BufferedReader(fr);
BufferedWriter bw = new BufferedWriter(fw);
char[] ch = new char[1024];
int len;
while((len = br.read(ch))!=-1){
bw.write(ch,0,len);
}
bw.flush();
long t2 = System.currentTimeMillis();
getTime(“Buffered字符数组”,t1,t2);
}
private static void getTime(String methodName,long t1, long t2){
System.out.println(methodName+ “耗时:” + (t2-t1) + “ms”);
}
}