import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
/**
* 类说明 :测试File、Buffered、 Data复制文件的用时
* 描述:首先写一个功能函数随机插入十万个数据到一个文件里,然后再写三个功能函数分别实现该文件的复制,最后在主函数里调用。
* @author 郭莹棋
* @date 2018年7月25日
*/
public class Test3 {
public static void init(String s) {
//首先随机生成十万个数据放到一个文件里
Random ra = new Random();
try {
FileWriter f = new FileWriter(s);
for(int i = 0;i < 100000;i++) {
int j = ra.nextInt(100);
f.write(String.valueOf(j)+ "\r\n");
}
f.close();
} catch(FileNotFoundException f) {
f.printStackTrace();
} catch(IOException i) {
i.printStackTrace();
}
}
/*
* s1:需要被复制的文件
* s2:需要被粘贴的文件
* tmp:文件里的内容
*/
public static void copyFile(String s1,String s2) {
long start = System.currentTimeMillis();
try{
FileInputStream f1 = new FileInputStream(s1);
FileOutputStream f2 = new FileOutputStream(s2);
int tmp;
//判断文件里是否有内容
while((tmp = f1.read()) != -1) {
f2.write(tmp);
}
//流的关闭操作
f1.close();
f2.close();
} catch(FileNotFoundException f) {
f.printStackTrace();
} catch(IOException i) {
i.printStackTrace();
}
long end = System.currentTimeMillis();
//22
System.out.println( end - start);
}
public static void copyBufferedFile(String s1,String s2) {
long start = System.currentTimeMillis();
try {
FileInputStream f1 = new FileInputStream(s1);
FileOutputStream f2 = new FileOutputStream(s2);
BufferedInputStream b1 = new BufferedInputStream(f1);
BufferedOutputStream b2 = new BufferedOutputStream(f2);
int tmp;
while((tmp = b1.read()) != -1) {
b2.write(tmp);
}
b1.close();
b2.close();
} catch(FileNotFoundException f) {
f.printStackTrace();
} catch(IOException i) {
i.printStackTrace();
}
long end = System.currentTimeMillis();
//2
System.out.println( end - start);
}
public static void copyDataFile(String s1,String s2) {
long start = System.currentTimeMillis();
try {
FileInputStream f1 = new FileInputStream(s1);
FileOutputStream f2 = new FileOutputStream(s2);
DataInputStream d1 = new DataInputStream(f1);
DataOutputStream d2 = new DataOutputStream(f2);
int tmp;
while((tmp = d1.read()) != -1) {
d2.writeInt(tmp);
}
d1.close();
d2.close();
} catch(FileNotFoundException f) {
f.printStackTrace();
} catch(IOException i) {
i.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println( end - start);
}
public static void main(String[] args) {
init("D:/myworld/gyq.txt");
copyFile("D:/myworld/gyq.txt","D:/myworld/gjc.txt");
//copyBufferedFile("D:/myworld/gyq.txt","D:/myworld/gjc.txt");
//copyDataFile("D:/myworld/gyq.txt","D:/myworld/gjc.txt");
}
}
所需用时:Data>File>Buffered