字节流数组读入
- 建立字节流读取,参数为字节数组读入流
InputStream bi = new BufferedInputStream(new ByteArrayInputStream(c));
- 建立读取字节数组,数组长度变量len
int len = 0;
byte[] flush = new byte[1024];
- 读取到需要操作的变量
String s = "";
while (-1 != (len = bi.read(flush))) {
s += new String(flush, 0, len);
}
System.out.println(s);
关闭流(可选)
bi.close();
字节流数组写出
- 建立字节数组输出流(新增方法,不可用多态)
ByteArrayOutputStream os = new ByteArrayOutputStream();
- 写入流
os.write(c, 0, c.length);
- 缓冲区中的内容赋值给dest,返回dest
byte[] dest;
dest = os.toByteArray();
return dest;
关闭流(可选)
bi.close();
完整操作代码
package cn.hxh.io.other;
import java.io.*;
public class ByteArrayDemo01 {
public static void main(String[] args) throws IOException {
read(write());
}
public static void read(byte[] c) throws IOException {
InputStream bi = new BufferedInputStream(new ByteArrayInputStream(c));
int len = 0;
byte[] flush = new byte[1024];
String s = "";
while (-1 != (len = bi.read(flush))) {
s += new String(flush, 0, len);
}
System.out.println(s);
}
public static byte[] write() throws IOException {
String str = "你好你好";
byte[] c = str.getBytes();
ByteArrayOutputStream os = new ByteArrayOutputStream();
os.write(c, 0, c.length);
byte[] dest;
dest = os.toByteArray();
return dest;
}
}