ByteArrayInputStream和ByteArrayOutputStream经常用在需要流和数组之间转化的情况!
说白了,FileInputStream是把文件当做数据源。ByteArrayInputStream则是把内存中的”某个字节数组对象”当做数据源。字节数组流只有字节流,没有字符流 ,属于节点流。
1、简单测试ByteArrayInputStream的使用:
public class TestByteArrayInputStream {
public static void main(String[] args) {
//将字符串转换成字节数组
byte[] buf = "你好,java!".getBytes();
read(buf);
}
public static void read(byte[] buf) {
ByteArrayInputStream bais = null;
try {
//该构造方法的参数是一个字节数组
bais = new ByteArrayInputStream(buf);
StringBuilder sb = new StringBuilder();
int temp = 0;
int num = 0;//用于保存读取的字节数
while((temp = bais.read()) != -1) {
sb.append((char)temp);
num++;
}
System.out.println(sb);
System.out.println("读取的字节数:" + num);
} finally {
try {
if(bais != null)
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果:
2、测试ByteArrayInputStream/ByteArrayOutputStream的使用:
public class TestByteArrayStream {
public static void main(String[] args) {
byte[] buf = write();//写对象方法,返回值为byte类型数组
read(buf);//读对象的方法
}
public static byte[] write() {
//创建字节数组流对象
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
//目的地是字节数组,底层默认创建一个长度为32的字节数组
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
//写出数据,将数据写入字节数组流中
oos.writeInt(97);
oos.writeDouble(3.14);
oos.writeChar('a');
oos.writeBoolean(true);
oos.writeObject(new Date(1000));
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭流
try {
if(oos != null)
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return baos.toByteArray();
}
public static void read(byte[] buf) {
//创建对象
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
//数据源是byte类型的数组
bais = new ByteArrayInputStream(buf);
ois = new ObjectInputStream(bais);
//读数据
System.out.println(ois.readInt());
System.out.println(ois.readDouble());
System.out.println(ois.readChar());
System.out.println(ois.readBoolean());
System.out.println(ois.readObject());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭流
try {
if(ois != null)
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果:
尚学堂百战程序员
百战程序员_IT6000集_影响6000万学习IT的中国人【官网】