综合对接流(图片到字节数组,字节数组到文件)

版权声明: https://blog.csdn.net/weixin_40072979/article/details/83539832

 跟文件复制类似,把图片文件读进去,以字节数组输出来,在把字节数组都进写出到文件,完成图片复制

package com.jianshun;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

/**
 * 1:图片读取到字节数组
 * 2:字节数组写出到文件
 */
public class IOTest09 {

	public static void main(String[] args) {
		//图片转成字节数组
		byte[] datas = fileToByteArray("p.jpg");
		System.out.println(datas.length);
		byteArrayToFile(datas,"p-byte.jpg");
	}
	
	/**
	 *1:图片读取到字节数组
	 *1):图片到程序             FileInputStream
	 *2):程序到字节数组         ByteArrayOutputStream 
	 */
	public static byte[] fileToByteArray(String filePath){
		//1:创建源与目的地
		File src = new File(filePath);
		//2:选择流
		InputStream is = null;
		ByteArrayOutputStream baos = null;
		try {
			is = new FileInputStream(src);
			baos = new ByteArrayOutputStream();
			//3:操作(分段读取)
			byte[] flush = new byte[1024*10];//缓冲容器
			int len = -1;//接受长度
			while((len = is.read(flush))!=-1){
				baos.write(flush, 0, len);//写出到字节数组中
			}
			baos.flush();
			return baos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//4:释放资源
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	/**
	 *2:字节数组写出到图片
	 *1):字节数组到程序 ByteArrayInputStream
	 *2):程序到文件 
	 */
	public static void byteArrayToFile(byte[] src,String pathString){
		//1,创建源
		File dest = new File(pathString);
		//2,选择流
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new ByteArrayInputStream(src);
			out = new FileOutputStream(dest);
			//3,操作(分段读取)
			byte[] flush = new byte[5];//缓冲容器
			int len =-1;
			while((len = in.read(flush)) != -1){
				out.write(flush, 0, len);
			}
			out.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//4:释放资源
			if(null != out){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_40072979/article/details/83539832
今日推荐