1.分别对比四种条件下复制一个7487K视频效率
- A方案:基本字节流一次读写一个字节
- B方案:基本字节流一次读写一个字节数组
- C方案:字节缓冲流一次读写一个字节
- D方案:字节缓冲流一次读写一个字节数组
⛔️ 输出结果:(如下)
2.代码
import java.io.*;
public class app {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
// 调用方法
copya();
// copyb();
// copyc();
// copyd();
long endTime = System.currentTimeMillis();
long Timer = endTime-startTime;
if(Timer<1000){
System.out.println("复制完成,耗时 >> "+Timer+"毫秒");
}else {
System.out.println("复制完成,耗时 >> "+(Timer/1000)+"秒");
}
}
// A方案 -- 普通字节流,单个数据
public static void copya() {
FileInputStream fileInput =null;
FileOutputStream fileOutput=null;
try {
fileInput = new FileInputStream("no1\\src\\static\\home_bg.mp4"); //读
fileOutput = new FileOutputStream("no1\\src\\static\\copya.mp4"); //写
int i = 0;
while ((i=fileInput.read())!=-1){
fileOutput.write(i);
}
}catch (IOException e) {
e.printStackTrace();
} finally {
if(fileInput!=null){
try {
fileInput.close();
fileOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// B方案 -- 普通字节流,数组
public static void copyb(){
FileInputStream fileInput =null;
FileOutputStream fileOutput=null;
try {
fileInput = new FileInputStream("no1\\src\\static\\home_bg.mp4"); //读
fileOutput = new FileOutputStream("no1\\src\\static\\copyb.mp4"); //写
byte[] byteArr = new byte[2048];
while (fileInput.read(byteArr)!=-1){
fileOutput.write(byteArr);
}
}catch (IOException e) {
e.printStackTrace();
} finally {
if(fileInput!=null){
try {
fileInput.close();
fileOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// c方案 -- 缓冲流,单个数据
public static void copyc(){
BufferedInputStream BInput = null;
BufferedOutputStream BOutput = null;
try {
BInput = new BufferedInputStream(new FileInputStream("no1\\src\\static\\home_bg.mp4"));
BOutput = new BufferedOutputStream(new FileOutputStream("no1\\src\\static\\copyc.mp4"));
int i=0;
while ((i=BInput.read())!=-1){
BOutput.write(i);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
BInput.close();
BOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// D方案 -- 缓冲流,数组
public static void copyd(){
BufferedInputStream BInput = null;
BufferedOutputStream BOutput = null;
try {
BInput = new BufferedInputStream(new FileInputStream("no1\\src\\static\\home_bg.mp4"));
BOutput = new BufferedOutputStream(new FileOutputStream("no1\\src\\static\\copyd.mp4"));
byte[] byteArr = new byte[1024];
while (BInput.read(byteArr)!=-1){
BOutput.write(byteArr);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
BInput.close();
BOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}