import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 通过字节流实现文件复制
*/
public class FileTest2 {
public static void main(String[] args) {
//调用方法 测试文件大小为750M
CopyFile("D:\\filetest\\b.zip","D:\\filetest\\a\\b.zip");
}
//定义复制方法
public static void CopyFile(String inPath,String osPath){
//记录时间,从1970年1月1日0时0分0秒到此时的毫秒值
long start = System.currentTimeMillis();
//定义读入流
FileInputStream in = null;
//定义写出流
FileOutputStream os = null;
try {
//创建读入流对象
in = new FileInputStream(inPath);
//创建写出流对象
os = new FileOutputStream(osPath);
//自建缓冲区,提升效率
byte[] bytes = new byte[1024*1024];
//5M
//byte[] bytes = new byte[5*1024*1024];
//依次测试对比
//1M 1.712s
//5M 13.494s
//10M 1.864s
//50M 7.422s
//100M 8.752s
//500M 13.871
//结论:数组长度会影响传输速度。(可以利用java提供的缓冲流BufferedInputStream 处理)
// 给定的长度越长,创建数组需要的时间约长
// 给定的长度越短,传输的次数越多
int len;
while ((len = in.read(bytes))!=-1){
//写出读取的字节流
os.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
in = null;
}
}
if (os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
os = null;
}
}
}
//记录结束时间
long end = System.currentTimeMillis();
//打印消耗时间,毫秒数
System.out.println("消耗时间"+(end-start));
}
}