Android将InputStream转换为String和byte[]


为什要将InputStream转换为String?因为要实现加密功能,加密函数的输入都是String。

  1. public static String inputStream2String (InputStream in) throws IOException   {   
  2.   
  3.         StringBuffer out = new StringBuffer();   
  4.         byte[]  b = new byte[4096];   
  5.         int n;  
  6.         while ((n = in.read(b))!= -1){   
  7.             out.append(new String(b,0,n));   
  8.     }  
  9.         Log.i("String的长度",new Integer(out.length()).toString());  
  10.         return  out.toString();   
  11. }     

通过各种getInputStream,就可以将HttpUrlconnection、输入文本流等等转换为String,当然还可以转化为byte[]

  1. public static byte[] InputStreamToByte(InputStream is) throws IOException {  
  2.            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();  
  3.            int ch;  
  4.            while ((ch = is.read()) != -1) {  
  5.             bytestream.write(ch);  
  6.            }  
  7.            byte imgdata[] = bytestream.toByteArray();  
  8.            bytestream.close();  
  9.            return imgdata;  
  10.           }  

相关内容