09 IO流(六)——ByteArray字节流、流对接

字节数组流

ByteArray流是节点流。

前面讲到的文件字节流,文件字符流,他们的源都是来自于pc硬盘。

本节要讲的字节数组流的源是来自于内存或网络。

它更合适用来处理来自网络的字节流。

由于源并不是来自于硬盘,所以流无需关闭。(写了关闭也不影响)

由于内存是有限的,为了避免内存占用过高,要对流进行一定限制。

任何东西包括对象,都可以转为字节数组,所以字节数组流是相当的方便。

字节数组输入流

数据来源不是文件,所以无需FileNotFoundException

字节数组输出流

由于字节数组输出流ByteArrayOutputStream它有新增方法,所以不能实现多态。(待验证20191123。)

字节数组输出流,它不能与文件对接,如果需要,则需要用以下方式对接文件:

字节数组输出流调用toByteArray()->字节文件输出流

不能与文件直接对接,所以字节数组输出流能做的就是调用toByteArray()返回一个字节数组(来自于流中的数据)。

流对接

流对接 练习:本地文件-(FileInputStream)->程序-(ByteArrayOutputStream)->数组-(ByteArrayInputStream)->程序-(FileOutputStream)->文件

import java.io.*;
public class IOTest01
{
	public static void main(String[] args){
		//源文件路径与目的路径
		String srcPath = "1.png";
		String destPath = "1_byte.png";
		//调用方法
		byte[] datas = fileToByteArray(srcPath);
		byteArrayToFile(datas,destPath);
	}
	/**
	*目的:模拟流对接
	*流程:本地文件-(FileInputStream)->程序-(ByteArrayOutputStream)->数组-(ByteArrayInputStream)->程序-(FileOutputStream)->文件
	*思路:拆分为读取方法与写入方法
	*/

	/**
	*读取方法:文件到字节数组
	*1.文件到程序
	*2.程序到数组
	*/
	public static byte[] fileToByteArray(String filePath){
		//1.文件源与目的地
		File src = new File("1.png");
		byte[] datas = null;//需要返回的数组
		//选择流
		InputStream fis = null;
		ByteArrayOutputStream bos = null;//由于字节数组输出流类有新增方法要使用,所以不能多态
		try{
		fis = new FileInputStream(filePath);
		bos = new ByteArrayOutputStream();
		//3.操作
		byte[] flush = new byte[1024*10];//缓冲区容器
		int len = -1;//接收长度
		while((len = fis.read(flush))!=-1){//读取
			bos.write(flush,0,len);//写入流
		}
		bos.flush();//刷新
		datas = bos.toByteArray();//从流得到数组
		return datas;//返回数组
		}catch(FileNotFoundException e){
			e.printStackTrace();
			System.err.println("找不到源文件");
		}catch(IOException e){
			e.printStackTrace();
			System.err.println("读写异常!");
		}finally{
			try{
				fis.close();
				System.out.println("文件到数组,成功!");
			}catch(IOException e){
				e.printStackTrace();
				System.err.println("流关闭失败");
			}
		}
	return null;
	}

	/**
	*从数组到文件
	*1.从数组到程序
	*2.从程序到文件
	*/
	public static void byteArrayToFile(byte[] src,String filePath){
		//1.文件源与目的地
		File dest = new File(filePath);
		//2.选择流
		InputStream is = null;
		OutputStream os = null;
		try{
			is = new ByteArrayInputStream(src);
			os = new FileOutputStream(dest);
		//3.操作
		byte[] flush = new byte[1024*10];
		int len = -1;
		while((len = is.read(flush))!=-1){//读到数组中
			os.write(flush,0,len);//写到文件
		}
		os.flush();//刷新
		}catch(IOException e){
			e.printStackTrace();
			System.err.println("读写失败!");
		}finally{
			try{
				os.close();
				System.out.println("数组到文件,成功!");
			}catch(IOException e){
				e.printStackTrace();
				System.err.println("流关闭失败!");
			}
		}
	}
}

  

原文地址:https://www.cnblogs.com/Scorpicat/p/11916842.html