ByteArrayInputStream 和 ByteArrayOutputStream
与FileInputStream和FileOutputStream相比,数据源由硬盘上的File文件,变为电脑上的或网络上的一块内存(字节数组),java可以直接访问内存,且可以直接释放内存(垃圾自动回收机制),即不用释放这段字节数组,即不用close()。
任何数组都可以转为字节数组。
内存空间有限,即使用较小的字节数组。
ByteArrayInputStream测试
code
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 测试字节数组流
* @author dxt
*
*/
public class IOTest06 {
public static void main(String[] args){
//1. 创建源
byte[] src = "My English is low!!!! How should I do?".getBytes();
//2. 选择源(多态)
InputStream is = null;
try{
is = new ByteArrayInputStream(src);
//3. 读取操作
byte[] flush = new byte[5]; //每次从内存读5个字节
int len = -1;
while((len = is.read(flush)) != -1){
String str = new String(flush, 0, len);
System.out.println(str);
}
//4. 释放资源
is.close(); //其实不需要,just keep the same style
} catch(IOException e){
e.printStackTrace();
} finally{
try{
if(null != is){
is.close(); //其实不需要,just keep the same style
}
} catch(IOException e){
e.printStackTrace();
}
}
}
}
result
ByteArrayOutputStream测试
code
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* 测试字节数组输出流
* 1. 创建源: 内部维护
* 2. 选择流: 不关联源
* 3. 操作: 写出内容
* 4. 释放资源: 可以不用
*
* 获取数据: toByteArray();
* @author dxt
*
*/
public class IOTest07 {
public static void main(String[] args){
//1. 创建源
byte[] dest = null; //不需要创建,因为不知道开辟多大内存
//2. 选择流 (需要使用BAOS中的新增方法,不能使用多态)
ByteArrayOutputStream baos = null;
try{
baos = new ByteArrayOutputStream(); //不需要指定目的地
//进行读入操作
String msg = "疑似银河落九天";
byte[] datas = msg.getBytes();
baos.write(datas, 0, datas.length); //写到字节数组中去
baos.flush(); //
//获取数据
dest = baos.toByteArray();
System.out.println(dest.length + "--" + new String(dest, 0, baos.size()));
}catch (IOException e){
e.printStackTrace();
}
}
}
result