其他流---字节流数组

时间:2022-07-22
本文章向大家介绍其他流---字节流数组,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

字节流数组读入

  1. 建立字节流读取,参数为字节数组读入流
	InputStream bi = new BufferedInputStream(new ByteArrayInputStream(c));
  1. 建立读取字节数组,数组长度变量len
	int len = 0;
	byte[] flush = new byte[1024];
  1. 读取到需要操作的变量
	String s = "";
	while (-1 != (len = bi.read(flush))) {
		s += new String(flush, 0, len);
	}
	System.out.println(s);
  1. 关闭流(可选)
	bi.close();

字节流数组写出

  1. 建立字节数组输出流(新增方法,不可用多态)
	ByteArrayOutputStream os = new ByteArrayOutputStream();
  1. 写入流
	os.write(c, 0, c.length);
  1. 缓冲区中的内容赋值给dest,返回dest
	byte[] dest;
	dest = os.toByteArray();
	return dest;
  1. 关闭流(可选)
	bi.close();

完整操作代码

package cn.hxh.io.other;

import java.io.*;

public class ByteArrayDemo01 {

	public static void main(String[] args) throws IOException {
		read(write());
	}


	public static void read(byte[] c) throws IOException {

		InputStream bi = new BufferedInputStream(new ByteArrayInputStream(c));
		int len = 0;
		byte[] flush = new byte[1024];
		String s = "";
		while (-1 != (len = bi.read(flush))) {
			s += new String(flush, 0, len);
		}
		System.out.println(s);

	}

	public static byte[] write() throws IOException {
		String str = "你好你好";
		byte[] c = str.getBytes();

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		os.write(c, 0, c.length);
		byte[] dest;
		dest = os.toByteArray();
		return dest;

	}
}