内存虚拟文件或者内存映像文件就是把内存中的一块数据存储缓冲区,虚拟成一个文件,原来该写入硬盘文件上的内容可以被写入到这个内存中,原来该从硬盘文件中读取的内容也可以在内存中读取。
而要在内存中定义一个大的内存缓冲区,这个内存缓冲区通常就是一个字节数组,在java中专门定义了这两个类用于以IO流的方式来完成对字节数组的读写来支持类似虚拟文件或者内存映像文件的类似功能
ByteArrayInputStream的两个构造函数
ByteArrayInputStream(byte [] buf) 使用一个字节数组当中的所有数据作为数据源,以后程序可以向输入流一样读取这个字节数组当中的数据
ByteArrayInputStream(byte[] buf,int offset,int length)
ByteArrayOutputStream的两个构造函数
ByteArrayOutputStream()创建一个32字节的缓冲区
ByteArrayOutputStream(int) 根据参数大小设置缓冲区
这两个构造函数创建的缓冲区在数据过多的时候都会自动增长
创建缓冲区以后,我们的程序就可以把它像虚拟文件一样写入数据,当写完数据,就可以调用ByteArrayOutputStream的一个方法把这其中的内容当做一个字节数组来返回
用这两个类可以提高运行效率,不用访问硬盘直接在内存中读写。
import java.io.*;
class ByteArrayTest {
public static void main(String[] args) {
// TODO: Add your code here
String tmp="abcdefjklmnopqrst";
byte [] src=tmp.getBytes();
ByteArrayInputStream input=new ByteArrayInputStream(src);
ByteArrayOutputStream output=new ByteArrayOutputStream();//这里不用传递字节数组,ByteArrayOutputStream会自动创建一个32字节的缓冲区用来写入数据"Creates a new byte array output stream."
transform(input,output);
byte[] result=output.toByteArray(); //public byte[] toByteArray() "Creates a newly allocated byte array. Its size is the current size of this output stream and the valid contents of the buffer have been copied into it."
System.out.println(new String(result));
System.out.println(new String(src));
}
public static void transform(InputStream in,OutputStream out){
int ch=0;
try{
while((ch=in.read())!=-1){
int upperCh=/*(int)*/Character.toUpperCase((char)ch); //char表示的范围比int小
out.write(upperCh);
}
}catch(Exception e){
e.printStackTrace();
}
}
}