图片的复制

思路:
fileToByteArray:把文件转换成字节数组
先用FileInputStream 的read 方法把文件字节流存到flush字节数组
在用ByteArrayOutputStream 的write方法从flush里读出来存到OutputStream的缓存数组里
最后把byteArrayOutputStream.toByteArray() return出去

byteArrayToFile:把字节数组转换成文件
先用ByteArrayInputStream 的read方法把OutputStream的缓存数组里的数据读取出来保存到flush数组里
在用FileOutputStream从flush数组里读取数据写入到目标文件


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IO_Test06 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub

		byteArrayToFile(fileToByteArray("13.png"), "16.png");

	}

	public static byte[] fileToByteArray(String srcPath) throws IOException {
		File srcFile = new File(srcPath);// 创建源
		InputStream iStream = new FileInputStream(srcFile);
		byte[] flush = new byte[1024];
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		int temp = -1;
		while ((temp = iStream.read(flush)) != -1) {//从srcFile里读并保存到flush里
			byteArrayOutputStream.write(flush);//从flush里读出来写到outputstream的缓存数组里,并不是存到flush数组里
		}
		iStream.close();
		return byteArrayOutputStream.toByteArray();

	}

	public static void byteArrayToFile(byte[] src, String filePath) throws IOException {
		File desFile = new File(filePath);
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(src);
		OutputStream oStream = new FileOutputStream(desFile);
		int len = -1;
		byte[] flush = new byte[1024];
		while ((len = byteArrayInputStream.read(flush)) != -1) {
			oStream.write(flush, 0, len);
		}
		oStream.flush();
		oStream.close();

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值