/**
* 通过字节流实现文件的复制,读写字节数组
*/
@Test
public void test1(){
//开始时间
long s = System.currentTimeMillis();
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream("我的视频.mp4");
fileOutputStream = new FileOutputStream("复制的视频1.mp4");
byte[] buf = new byte[8192];
int n;
while ((n = fileInputStream.read(buf)) != -1){//已读为主导
//把读到的数据写入到输出流中
fileOutputStream.write(buf,0,n);//读到几个,写几个
}
}catch (IOException e){
e.printStackTrace();
}finally {
if (fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//结束时间
long e=System.currentTimeMillis();
System.out.println("复制时间: " + (e-s) + "毫秒");
}
/**
* 通过字节缓冲流实现文件的复制,读写字节数组
*/
@Test
public void test2(){
//开始时间
long s=System.currentTimeMillis();
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
//包装,对象关联
bufferedInputStream = new BufferedInputStream(new FileInputStream("我的视频.mp4"));
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("缓冲流视频.mp4"));
byte[] buf = new byte[8192];
int n;
while ((n = bufferedInputStream.read(buf)) != -1){
bufferedOutputStream.write(buf,0,n);
}
}catch (IOException e){
e.printStackTrace();
}finally {
if (bufferedInputStream != null){
try {
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedOutputStream != null){
try {
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//结束时间
long e=System.currentTimeMillis();
System.out.println("复制时间: " + (e-s) + "毫秒");
}
两种方式的效率对比:
字节流,读写字节数组方式:142秒
字节缓冲流,读写字节数组方式:138秒
(实验多次,差距不是很大,视频大小为5GB左右)