InputStream与String 转换

来源:互联网 发布:unity3d transform 编辑:程序博客网 时间:2024/04/30 05:43

转自:http://wesker0918.iteye.com/blog/286642和http://www.oschina.net/code/snippet_54371_3138两处

String --> InputStream

  1. InputStream StringToInputStream(String str){  
  2.     ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());  
  3.     return stream;  


InputStream --> String

  1. String inputStreamToString(InputStream is){  
  2.     BufferedReader in = new BufferedReader(new InputStreamReader(is));  
  3.     StringBuffer buffer = new StringBuffer();  
  4.     String line = "";  
  5.     while ((line = in.readLine()) != null){  
  6.         buffer.append(line);  
  7.     }  
  8.     return buffer.toString();  

另外一处

int i = -1;//org.apache.commons.io.output.ByteArrayOutputStreamByteArrayOutputStream baos = new ByteArrayOutputStream();while ((i = is.read()) != -1) {baos.write(i);}String content = baos.toString();
int i = -1;byte[] b = new byte[1024];StringBuffer sb = new StringBuffer();while ((i = is.read(b)) != -1) {sb.append(new String(b, 0, i));}String content = sb.toString();