字节数组流,即向内存数组读/取数据,实现数据在流与流之间的传递。
与字节流别无二致。
-
ByteInputStream:
package SAMPLE.IO流;
import java.io.*;
/*文件 字节数组输入流
1、确定源:字节数组,不要太大
2、选择流 文件输入流:ByteArrayInputStream
3、操作 (没有“文件不存在”异常)
4、释放资源,可以不处理
*/
public class ByteArrayIn字节数组流 {
public static void main(String[] args) {
//创建源
byte[] src = "talk is cheap, show me the code".getBytes();
//选择流
ByteArrayInputStream bais = null;//扩展作用域
try {
bais = new ByteArrayInputStream(src);
//操作(分段读取)
byte[] flush = new byte[5];//缓存容器,字节流为字节数组。
int len = -1;//接收长度
while((len=bais.read(flush))!=-1){
//字节数组-->字符串(解码)
String str = new String(flush,0,len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取失败");
}finally {
//此处close为空方法,字节数组会通过垃圾回收机制刷新
try {
if(bais!=null)
bais.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("关闭输入流失败");
}
}
}
}
小结:
1、字节数组流不涉及对系统文件的操作,而是在内存中进行维护。
2、基于垃圾回收机制释放资源,close()变得没有必要。
-
ByteOutputStream:
package SAMPLE.IO流;
import java.io.*;
/*文件 字节数组输出流
1、确定源(内部维护)
2、选择流 不关联源
3、操作
4、释放资源 可以不用
*/
public class ByteArrayOut字节数组流 {
public static void main(String[] args) {
//创建源
byte[] dest = null;
//选择流
ByteArrayOutputStream baos = null;//扩展作用域
try {
baos = new ByteArrayOutputStream();//不关联源,无源内数据入流,而是流内数据入源
//操作(写出)
String msg = "show me the code";
byte[] datas = msg.getBytes();//字符串-->字节数组(编码)
baos.write(datas,0,datas.length);//追加形式
baos.flush();
//获取数据
dest = baos.toByteArray();
System.out.println(new String(dest,0,dest.length));
} catch (IOException e) {
e.printStackTrace();
System.out.println("写出失败");
}finally {
//释放资源close,在此处可有可无
try {
if(baos!=null)
baos.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("关闭输出流失败");
}
}
}
}
小结:
1、不关联系统文件,写出的数据在内存中维护。
2、close()不必要。