字节流文件拷贝使用缓冲数组提高效率

package io;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class Test4 {


//拷贝本件
//先使用输入流把文件读取
//然后使用输出流把内容写出到文件中
public static void main(String[] args) throws IOException {

//一个字节一个字节读取   然后一个字节一个字节写入
FileInputStream file=new FileInputStream("e://aa//1.mp4");
FileOutputStream file1=new FileOutputStream("e://2.mp4");
int read=file.read();
while(read!= -1){
System.out.println(read);
file1.write(read);
read=file.read();

}

//关流
file1.close();
file.close();


}

}



运行了10s才拷贝7.84MB,原文件45.6MB

现在用缓冲数组进行拷贝

package io;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class Test5 {
public static void main(String[] args) throws IOException {

//一个字节一个字节读取   然后一个字节一个字节写入
FileInputStream file=new FileInputStream("e://aa//1.mp4");
FileOutputStream file1=new FileOutputStream("e://2.mp4");
//int read=file.read();
//file1.write(b, off, len);    b是缓冲数组   off  目标数组的b的起始偏移量   len 读取的最大字节量
byte []arr=new byte[1024];
int i=file.read(arr);//一次性读取1024个字节  并将读取的数据存储到arr中  返回值是实际上读取的byte长度

//一次性读取1024个字节   从偏移量开始写多少个字节   也是实际读取了多少个字节
while(i!= -1){
file1.write(arr, 0, i);
i=file.read(arr);


}

//关流
file1.close();
file.close();
}

}


运行过一段时间  3s左右  拷贝完成




猜你喜欢

转载自blog.csdn.net/yuanboqi/article/details/80199830