节点流
字节数组输入流:ByteArrayInputStream read(byte[] b,int off,int len)+close()
输出流:ByteArrayOutputStream write(byte[] b,int off,int len)+toByteArray() 新增方法不要使用多态
import java.io.*;
public class Demo06 {
public static void main(String[] args) throws IOException {
reader(write());
}
public static byte[] write() throws IOException {
//目的地
byte[] dest;
//选择流 不同点
ByteArrayOutputStream bos=new ByteArrayOutputStream();//不使用多态
String string="爱我大中国";
byte[] data=string.getBytes();
//写入数据
bos.write(data,0,data.length);
dest=bos.toByteArray();
bos.flush();
bos.close();
return dest;
}
public static void reader(byte[] data) throws IOException {
//输入流
InputStream is=new BufferedInputStream(new ByteArrayInputStream(data));
byte[] flush=new byte[1024];
int len=0;
while(-1!=(len=is.read(flush))){
System.out.println(new String(flush,0,len));
}
is.close();
}
}
字节数组流和文件流对接
import java.io.*;
/**
* 文件输入流->程序->字节数组流
* 字节数组流->程序->文件输出流
*/
public class Demo07 {
public static void main(String[] args) throws IOException {
byte[] b=getByteArrayStream("D:/test.txt");
for(int i=0;i<100;i++){
toFileFromByteArray(b,"D:test2.txt");
}
}
public static byte[] getByteArrayStream(String srcPath) throws IOException {
//文件源
File src=new File(srcPath);
//目的地
byte[] dest=null;
//文件输入流
InputStream is=new BufferedInputStream(new FileInputStream(src));
//字节数组输出流不能使用多态
ByteArrayOutputStream bos=new ByteArrayOutputStream();
//不断读取文件 写出到字节数组流中
byte[] flush=new byte[1024];
int len=0;
while(-1!=(len=is.read(flush))){
//写出到字节数组流中
bos.write(flush,0,len);
}
bos.flush();
dest=bos.toByteArray();
bos.close();
is.close();
return dest;
}
public static void toFileFromByteArray(byte[] src1,String destPath) throws IOException {
//创建源
//目的地
File dest=new File(destPath);
//字节数组输入流可以使用多态
InputStream is=new BufferedInputStream(new ByteArrayInputStream(src1));
OutputStream os=new BufferedOutputStream(new FileOutputStream(dest,true));
//不断读取
byte[] flush=new byte[1024];
int len=0;
while(-1!=(len=is.read(flush))){
os.write(flush,0,len);
}
os.flush();
is.close();
os.close();
}
}