天天看点

Stream 转换为 String

将接收到的InputStream转换为String

public   String   inputStream2String   (InputStream   in)   throws   IOException   {

        StringBuffer   out   =   new   StringBuffer();

        byte[]   b   =   new   byte[4096];

        for   (int   n;   (n   =   in.read(b))   !=   -1;)   {

                out.append(new   String(b,   0,   n));

        }

        return   out.toString();

}

public   static   String   inputStream2String(InputStream   is)   throws   IOException{

ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream();

int   i=-1;

while((i=is.read())!=-1){

baos.write(i);

}

return   baos.toString();

}

将String发送出去

private void str2Stream(String data) throws Exception{

     OutputStream os = null;

     try{

     os = new ByteArrayOutputStream();

     os.write(data.getBytes(), 0, data.length());

     } finally{

      if(os != null)

       os.close();

     }

    }