优化前:执行的io操作过多

package com.yqq.app6;

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

/**
* @Author yqq
* @Date 2021/11/11 21:18
* @Version 1.0
*/
public class FileStreamDemo {
public static void main(String[] args) {
FileInputStream fs = null;
FileOutputStream fo = null;
try {
fs = new FileInputStream("E:/pic/2.png");
fo =new FileOutputStream("E:/pic/2cop.png");
int tem = 0;
while ((tem = fs.read())!=-1){
fo.write(tem);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(fs!=null){
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fo!=null){
try {
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

优化后:

package com.yqq.app6;

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

/**
* @Author yqq
* @Date 2021/11/11 21:34
* @Version 1.0
*/
public class FileStreamBuffDemo {
public static void main(String[] args) {
FileInputStream fs = null;
FileOutputStream fo = null;
try {
fs = new FileInputStream("E:/pic/2.png");
fo =new FileOutputStream("E:/pic/2cop.png");
//创建一个字节缓冲区,提高读写效率
byte[] buff = new byte[1024];
int tem = 0;
while ((tem = fs.read(buff))!=-1){
fo.write(buff,0,tem);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(fs!=null){
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fo!=null){
try {
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

通过创建一个指定长度的字节数组作为缓冲区,以此来提高 IO 流的读写效率。该方式 适用于读取较大图片时的缓冲区定义。注意:缓冲区的长度一定是 2 的整数幂。一般情况下 1024 长度较为合适