---
title: "输入流的缓存"
author: "sd4886656"
date: "2011-10-24T13:39:11Z"
tags: []
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2011-10-24T14:00:08Z"
id: 1210339
url: "https://sd4886656.iteye.com/blog/1210339"
---

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();//
 
```