2011年9月5日

轉錄:如何把InputStream變成字串?

(出處: www.kodejava.org)
Learn Java by Examples - How do I convert InputStream to String?:

public String convertStream2String(InputStream is) throws IOException{
 if (is != null) {
   Writer writer = new StringWriter();
   char[] buffer = new char[1024];
   try {
     Reader rr=new BufferedReader(new InputStreamReader(is,"UTF-8"));
     int n;
     while ((n = rr.read(buffer)) != -1) 
             writer.write(buffer, 0, n);
   }finally {
     is.close();
   }
   return writer.toString();
 }else 
  return "";
}

沒有留言: