内存流
在Java中,针对内存操作提供了以下两组类:
- 字节内存流:ByteArrayInputStream(内存字节输入流)、ByteArrayOutputStream(内存字节输出流);
- 字符内存流:CharArrayReader(内存字符输入流)、CharArrayWriter(内存字符输出流)。
这两者的唯一区别就在于操作数据类型上,字节内存流使用byte数据类型,而字符内存流操作则使用char数据类型,但是他们的基本结构相同,博主着重讲字节内存流的使用。
字节内存流定义的构造方法如下:
- ByteArrayInputStream类构造:public ByteArrayInputStream(byte[] buf);
- ByteArrayOutputStream类构造:public ByteArrayOutputStream()。
内存流的操作实质上就是将数据首先保存到内存中,然后利用IO流操作进行单个字节的处理。
例:实现一个小写字母转大写字母的操作
- 本程序不使用String类中提供的toUpperCase()方法,而是利用IO操作,将每一个字节进行大写字母的转换;
- 为了方便地实现字母的转大写操作(避免不必要的字符也被转换)可以借助Character包装类的方法。
转小写字母:public static char toLowerCase(char ch);
转小写字母(利用字母编码转换):public static int toLowerCase(int codePoint);
转大写字母:public static char toUpperCase(char ch);
转大写字母(利用字母编码操作):public static int toUpperCase(int codePoint)。
package Project.Study.TMemoryStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class Test1 {
public static void main(String[]args)throws Exception{
String str="Hello World!!!";//需要转换的字符串
//本次将通过内存操作流实现转换,先将数据保存在内存流里面,再从里面取出每一个数据
//将所有要读取的数据设置到内存输入流中,本次利用向上转型为InputStream类实例化
InputStream inputStream=new ByteArrayInputStream(str.getBytes());
OutputStream outputStream=new ByteArrayOutputStream();//为了能够将所有的内存流数据取出,可以使用ByteArrayOutputStream
int temp=0;
//经过此次循环后,所有数据都将保存在内存输出流对象中
while((temp=inputStream.read())!=-1){//每次读取一个数据
//将读取进来的数据转换为大写字母,利用Character.toUpperCase()可以保证只转换字母
outputStream.write(Character.toUpperCase(temp));//字节输出流
}
System.out.println(outputStream);//调用toString()方法
inputStream.close(); //关闭输入流
outputStream.close(); //关闭输出流
}
}
//结果:
//HELLO WORLD!!!
在ByteArrayOutputStream类里面存在一个重要的方法,可以通过内存输出流取得全部数据:public byte[] toByteArray(),此方法可以将所有暂时保存在内存输出流中的字节数据全部以字节数组的形式返回,而利用这样的方法,就可以实现多个文件的合并读取操作。
例:实现文件的合并读取
package Project.Study.TMemoryStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class Test2 {
public static void main(String[]args)throws Exception{
File fileA=new File("d:"+File.separator+"Test1"+File.separator+"test.txt"); //文件路径
File fileB=new File("d:"+File.separator+"Test1"+File.separator+"test2.txt");
InputStream inputStreamA=new FileInputStream(fileA); //字节输入流
InputStream inputStreamB=new FileInputStream(fileB);
ByteArrayOutputStream output=new ByteArrayOutputStream();//内存输出流
int temp=0; //每次读一个字节
while((temp=inputStreamA.read())!=-1){ //循环读取数据
output.write(temp); //将数据保存到输出流
}
while((temp=inputStreamB.read())!=-1){
output.write(temp);
}
//现在所有的内容都保存在了内存输出流里面,所有的内容变为字节数组取出
byte[]data=output.toByteArray(); //取出全部数据
output.close(); //关闭输出流
inputStreamA.close();
inputStreamB.close();
System.out.println(new String(data)); //字节转换为字符串输出
}
}
//结果:
//Hello World!!!
//Hi!!!