JAVA IO流之对接流(使用文件字节流和字节数组流完成图片的复制)

文件字节流和字节数组流对接完成复制图片

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();
 		   }
  	  }
   }
  }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值