内存流的作用:假设某一种应用需要进行IO操作,但又不希望在磁盘上产生一些文件时,就可以将内存作为一个临时文件进行操作。
字节内存流:ByteArrayInputStream、ByteArrayOutputStream;
字符内存流:CharArrayReader、CharArrayWriter。
字节内存流与字符内存流的区别:两者的唯一的区别就在于操作数据类型上。(Byte、Char)
实现一个小写字母转大写字母的操作:
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
String str ="Hello*Word!!!";
//通过内存流实现转换。先将数据保存在内存中,然后从里面取出每一个数据
//将所有要读取的数据设置到内存输入流之中,本次利用向上转型为InputStream实例化
InputStream input = new ByteArrayInputStream(str.getBytes());
//将所有内存数据取出
OutputStream output = new ByteArrayOutputStream();
int temp = 0;
//经过此次循环,所有的数据都将保持在内存输出流对象之中
while((temp = input.read()) !=-1){ //每次读取一个数据
output.write(Character.toUpperCase(temp)); //字节输出流
}
System.out.println(output);
input.close();
output.close();
}
}
以程序操作为例:
|-输出 :程序>>>OutputStream<<<文件
|-输入 :程序>>>lnputStream<<<文件
以内存操作为例:
|-输出:程序>>>lnputStream>>>内存
|-输入:程序<<<OutputStream<<<内存
通过内存流实现文件的合并读取:
import java.io.*;
public class Test2 {
public static void main(String args[]) throws Exception{
File fileA = new File("D:" +File.separator + "AAA.txt");
File fileB = new File("D:" +File.separator + "BBB.txt");
InputStream inputA = new FileInputStream(fileA); //字节输入流
InputStream inputB = new FileInputStream(fileB); //字节输入流
ByteArrayOutputStream output = new ByteArrayOutputStream(); //内存输出流
int temp = 0 ;
while((temp=inputA.read()) != -1){
output.write(temp); //循环读取数据,并将数据保存到输出流
}
while( (temp = inputB.read()) != -1){
output.write(temp);
}
byte data[] = output.toByteArray(); //取出全部数据
output.close();
inputA.close();
inputB.close();
System.out.println(new String(data));
}
}