Java IO 流-- 字节数组流ByteArrayInPutStream ByteArrayOutPutStream

字节数组流输于缓冲流,放在jvm内存中,java可以直接操作。我们使用时可以不用关闭,交给GC垃圾回收机制处理、
当然我们为了保持良好习惯和代码一致性也可以加上关闭语句。

当其实我么打开ByteArrayInputStream 和 ByteArrayOutputStream 源码可以发现字节数组里的colse() 方法是个空方法:
/**
     * Closing a <tt>ByteArrayInputStream</tt> has no effect. The methods in
     * this class can be called after the stream has been closed without
     * generating an <tt>IOException</tt>.
     */
    public void close() throws IOException {
    }

所以我们在使用时关闭不关闭都不影响

接下来我们来写一段代码实现:
文件–> 程序–>字节数组流–>程序—>文件 的操作:

package com.xzlf.io;

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

/**
 * 1、图片读取到字节数组
 * 2、字节数组读取到文件
 * @author xzlf
 *
 */
public class IOTest03 {

	public static void main(String[] args) {
		// 图片到字节数组
		byte[] datas = fileToByteArray("src/1.jpg");
		System.out.println(datas.length);
		// 字节数组到图片
		byteArrayToFile(datas, "src/1-byte.jpg");
	}
	
	/**
	 * 图片读取到字节数组
	 * 1、图片到程序  FileInputStream
	 * 2、程序到字节数组 ByteArrayOutputStream
	 * @param filePath
	 * @return
	 */
	public static byte[] fileToByteArray(String filePath) {
		// 1、创建源
		File src = new File(filePath);
		
		// 2、选择流
		FileInputStream is = null;
		ByteArrayOutputStream bos = null;
		try {
			is = new FileInputStream(src);
			bos = new ByteArrayOutputStream();
			byte[] flush = new byte[1024];// 缓冲容器
			int len = -1;
			// 3、操作(分段读取)
			while((len = is.read(flush)) != -1) {
				bos.write(flush, 0, len);// 写出到字节数组
			}
			bos.flush();
			return bos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			// 4、释放资源
			try {
				if(is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 字节数组写出到图片
	 * 1、字节数组到程序  FileInputStream
	 * 2、程序到图片 ByteArrayOutputStream
	 * @param filePath
	 * @return
	 */
	public static void byteArrayToFile(byte[] src, String filePath) {
		// 1、创建源
		File dest = new File(filePath);
		
		// 2、选择流
		FileOutputStream os = null;
		ByteArrayInputStream bis = null;
		try {
			os = new FileOutputStream(dest);
			bis = new ByteArrayInputStream(src);
			byte[] flush = new byte[1024*10];// 缓冲容器
			int len = -1;
			// 3、操作(分段读取)
			while((len = bis.read(flush)) != -1) {
				os.write(flush, 0, len);// 写出到文件
			}
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			// 4、释放资源
			try {
				if(os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

运行测试:
在这里插入图片描述

其实很简单,大家可以拿到自己电脑上测试一下。

posted @ 2020-03-27 02:29  行者老夫  阅读(266)  评论(0编辑  收藏  举报