内存流——​ByteArrayOutputStream,ByteArrayInputStream,CharArrayReader,CharArrayWriter

1、 什么是内存流

​ 当输出流的目的,和输入流的源是内存时,这样的流称之为内存流。

​ ByteArrayOutputStream:内存流的输出流

​ ByteArrayInputStream:内存流的输入流,它是唯一一种能够直接从网络上获取二进制数据的流

​ CharArrayReader:内存流中的输入流

​ CharArrayWriter:内存流中的输出流

​ ByteArrayInputStream主要完成将内容从内存读入程序之中,而ByteArrayOutputStream的功能主要是将数据写入到内存中。

2、内存流构造方法

ByteArrayInputStream是输入流的一种实现,它有两个构造函数,每个构造函数都需要一个字节数组来作为其数据源:

ByteArrayInputStream(byte[] buf)

ByteArrayInputStream(byte[] buf,int offse , int length)

​ ByteArrayOutputStream是输出流的一种实现,它有两个构造函数:

ByteArrayOutputStream():内存中分配了一个字节数组。

BuyteArrayoutputStream(int):创建一个新的 byte 数组输出流,它具有指定大小的缓冲区容量(以字节为单位)

1.3 写数据到内存流和从内存流读数据

​ 如果程序在运行过程中要产生一些临时文件,可以采用虚拟文件方式实现(其实是一段内存),JDK中提供了ByteArrayInputStream和ByteArrayOutputStream两个类可实现类似于内存虚拟文件的功能。

通过内存流写数据: 

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class Test {

	public static void writeByteArray(String msg) {
		ByteArrayOutputStream baos = null;

		try {
			baos = new ByteArrayOutputStream();
			baos.write(msg.getBytes());
			baos.flush();

			// 1.通过toString()得到缓冲区数据
			// System.out.println(baos.toString());

			// 2.通过toByteArray()方法得到一个byte数组
			byte[] b = baos.toByteArray();
			String str = new String(b);
			System.out.println("str:" + str);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) {
		String msg = "hello world";
		Test.writeByteArray(msg);
	}
}

通过内存流读取数据:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class Test {

	public static void readByteArray(String msg) {
		ByteArrayOutputStream baos = null;
		ByteArrayInputStream bais = null;

		try {
			baos = new ByteArrayOutputStream();
			baos.write(msg.getBytes());
			baos.flush();

			bais = new ByteArrayInputStream(baos.toByteArray());
			byte[] b = new byte[1024];
			int len = bais.read(b);
			System.out.println("len:" + len);
			String str = new String(b, 0, len);
			System.out.println("str:" + str);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		String msg = "hello world";
		readByteArray(msg);
	}
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值