ITeye博客

输入流的缓存

sd4886656 · 2011-10-24 13:39 · Android · 移动开发 · Markdown

java网络访问时,一般都会向服务器获取一个输入流 Inpustream in

这个流是不能读第二次的,比方这个流既要decode成Bitmap图片,又要将此图片写本地的话,第二次读的时候,这个流就失效了。

网上有人建议用mark() 来重读,但是有些情况下in是不支持mark()的

所以必须用byte [] 或者神马来缓存一下(当然读一次就够了的情况是不需要了)

 

ByteArrayOutputStream out = ByteArrayOutputStream();
int ch = -1;
while( (ch = os.read()) !=-1 ){
	out.write(ch);
}
byte [] buf = out.toByteArray();// InputStream 转 byte数组
//相反 byte数组也可以转化成流 
ByteArrayInputStream in = new ByteArrayInputStream(array);//一行代码,byte [] 转流

File file = new File(path+File.separator+id+tname);
					
try {
	file.createNewFile();
} catch (IOException e) {
	e.printStackTrace();
	return false;							
}

DataOutputStream out = new DataOutputStream(new FileOutputStream(file));
int ch;
while((ch = in.read()) != -1){
	out.write(ch);
}
out.flush();
out.close();//
 

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。