String str ="a,b,c" ;
ByteArrayInputStream bos=new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream dis =new ByteArrayOutputStream();
这两个一个是往内存里写入str字符串数据 一个是从内存中读取数据吧。。
不过这两个有必要配合着一起使吗?
我干嘛要先把他写入到内存中 在从内存中读取呢?
我直接 try{
dis.write(str.getBytes());
}catch (Exception e){
e.printStackTrace();
}不是也可以把数据写入进去吗? 还是我把概念弄混了。。望高手指点
ByteArrayInputStream bos=new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream dis =new ByteArrayOutputStream();
这两个一个是往内存里写入str字符串数据 一个是从内存中读取数据吧。。
不过这两个有必要配合着一起使吗?
我干嘛要先把他写入到内存中 在从内存中读取呢?
我直接 try{
dis.write(str.getBytes());
}catch (Exception e){
e.printStackTrace();
}不是也可以把数据写入进去吗? 还是我把概念弄混了。。望高手指点
ByteArrayOutputStream 可以在你需要循环从InputStream中读取字节数组时很有帮助
比如
for(xxx)
{
byte[] xx = new byte[100]
is.read(100)//简写,每次读取100个给数组
byteArrayOutputStream.write(xx);
}
然后出来之后整个输入流就转到byteArrayOutputStream,想要得到数组就toArray就很方便了
说了一堆 搞了半天连最基本的都错了
import java.io.*;public class ByteArrayOutputStreamDemo01{
public static void main(String args[])throws Exception{
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write("我".getBytes());
byte[]b = out.toByteArray();
out.close();
ByteArrayInputStream in = new ByteArrayInputStream(b);
byte[]b2 = new byte[1024];
int len = in.read(b2);
String str = new String(b2,0,len);
System.out.println(str);
in.close();
}
}