7.字节数组输入输出流:什么是字节数组输入输出流???
学习:第7遍
1.什么是字节数组输入输出流???
流(数据)的来源或目的地并不一定是文件,也可以是内存中的一块空间,例如一个字节数组
ByteArrayInputStream 字节数组输入流:从字节数组中读取数据,即将字节数组当作流输入的来源
ByteArrayOutputStream 字节数组输出流:将数据写出到内置的字节数组中,即将字节数组当作流输出的目的地 方法:os.toByteArray() 作用:获取内置的字节数组中的数据
public class Test{
public static void main(String
[] args
) {
test01();
test02();
}
public static void test01(){
byte[] data
="welcome to java".getBytes();
try {
InputStream is
= new ByteArrayInputStream(data
);
int i
=-1;
while((i
=is
.read())!=-1){
System
.out
.print((char)i
);
}
} catch (IOException e
) {
e
.printStackTrace();
}
}
public static void test02(){
try {
ByteArrayOutputStream os
= new ByteArrayOutputStream();
os
.write("hello".getBytes());
os
.flush();
byte[] buffer
= os
.toByteArray();
System
.out
.println(new String(buffer
));
System
.out
.println(os
.toString());
} catch (IOException e
) {
e
.printStackTrace();
}
}
}