13.字符数组流
经常使用在流和数组直接的转换
-
字节数组输入流:ByteArrayInputStream 说白了,就是把内存中的字节数组对象当作数据源
import java.io.ByteArrayInputStream;
public class Dome11 {
public static void main(String[] args) {
//创建字节数组
byte[] arr = "abcd".getBytes();
ByteArrayInputStream bs = null;
try {
bs = new ByteArrayInputStream(arr);//字节数组输入流
StringBuilder sb = new StringBuilder();
int temp = 0;
while ((temp = bs.read()) != -1) {
sb.append((char) temp);
}
System.out.println(sb.toString());
} finally {
try {
if (bs != null) {
bs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

-
字节数组输出流
import java.io.ByteArrayOutputStream;
public class Dome12 {
public static void main(String[] args) {
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();//创建字节数组输入流对象
StringBuilder sb = new StringBuilder();
//写入内容~这里会自动把字符类型转化成对应的十进制整数
bos.write('a');
bos.write('b');
//写入的内容到一个字节数组了
byte[] data = bos.toByteArray();
//遍历循环
for (int i = 0; i < data.length; i++) {
sb.append((char) data[i]);
System.out.println(data[i]);
}
System.out.println(sb.toString());
} finally {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
}


浙公网安备 33010602011771号