字节数组流
【小城贝尔】
灵活便捷数组源,大量数据不可传 。
写出操做无多态,变成数组惹人爱。
操作资源内存上,无需关闭资源方。
字节数组流初测
public static void main(String[] args)throws Exception{
byte[] bs = "灵活便捷数组源,大量数据不可传 。写出操做无多态,变成数组惹人爱".getBytes("UTF-8");
InputStream bin = new ByteArrayInputStream(bs);
byte[] bss = new byte[3];//java中汉字三个字节
int len = -1;
while((len = bin.read(bss)) != -1){
//转换成string
System.out.println(new String(bss,0,len));
}
//空方法空实现
bin.close();
}
字节数组流写入写出
public static void main(String[] args) {
byte[] bs = "灵活便捷数组源,大量数据不可传 。写出操做无多态,变成数组惹人爱".getBytes();
InputStream binput = null;
ByteArrayOutputStream bout = null;
try {
binput = new ByteArrayInputStream(bs);
bout = new ByteArrayOutputStream();
byte[] bss = new byte[30];
int len = -1;
while ((len = binput.read(bss)) != -1){
bout.write(bss,0 , len);
}
bout.flush();
}catch (IOException e){
e.printStackTrace();
}
//输出写入的数组
byte[] bous = bout.toByteArray();
System.out.println(new String("from boutTo Aarry : "+new String(bous)));
}
将文件写入数组然后再将数组写出到文件
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
InputStream binput = null;
ByteArrayOutputStream bout = null;
try {
in = new FileInputStream("E:/java1.mp4");
out = new FileOutputStream("E:/javaTeache.mp4");
bout = new ByteArrayOutputStream();
//将数据写入字节数组流
byte[] ins = new byte[1024];
int len = -1;
while ((len = in.read(ins))!= -1){
bout.write(ins,0,len);
}
bout.flush();
//存储字节资源的数组
byte[] bytes = bout.toByteArray();
//将数组中的数据读出来在写入文件
binput = new ByteArrayInputStream(bytes);
byte[] outs = new byte[1024];
int outLen = -1;
while( (outLen = binput.read(outs)) != -1){
out.write(bytes,0,outLen);
}
out.flush();
}catch (IOException e){
e.printStackTrace();
}
}