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);
}
}