文件字节流和字节数组流对接完成复制图片
1,过程示意图
程序主要起中转的作用。
这个过程主要模拟的是通过网络来向不同机器传输文件的底层思想。
2,代码演示
import java.io.*;
public class TestIO {
public static void main(String[] args) {
//图片转换为字节数组
byte[] dest=FileToByteArray("a.jpg");
System.out.println(dest.length);
//将字节数组还原为图片
ByteArrayTOFile(dest,"new-a.jpg");
}
//FileToByteArray方法:将图片存储到字节数组中
//1.图片到程序(FileInputStream)
//2.程序到字节数组(ByteArrayOutputStream)
public static byte[] FileToByteArray(String filePath) {
//创建源头与目的地字节数组
File file=new File(filePath);
byte[] dest=null; //存放图片转换为字节数据的字节数组
//选择流
InputStream is=null;
ByteArrayOutputStream baous=null;
try {
is=new FileInputStream(file);
baous=new ByteArrayOutputStream();
//相关操作
byte[] flush=new byte[1024*10];//缓冲容器
int len;
while((len=is.read(flush))!=-1) {
//分段读取
baous.write(flush, 0, len); //写出字节数组中
}
baous.flush();//刷新操作,避免数据滞留
dest=baous.toByteArray();
return dest;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(is!=null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
//ByteArrayTOFile方法:将字节数组写出到图片
//1.字节数组读取到文件(ByteArrayInputStream)
//2.程序还原图片(FileOutputStream)
public static void ByteArrayTOFile(byte[] src,String filePath) {
//创建源
File file=new File(filePath);
//选择流
ByteArrayInputStream baius=null;
FileOutputStream os=null;
try {
baius=new ByteArrayInputStream(src);
os=new FileOutputStream(file,true);
//相关操作
byte[] flush=new byte[1024*10];//缓冲容器
int len;
while((len=baius.read(flush))!=-1) {
os.write(flush, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(os!=null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}