String and InputStream convert each other

Source: Internet
Author: User

1.String to InputStream

String str = "string-to-inputstream conversion";

InputStream In_nocode = new Bytearrayinputstream (Str.getbytes ());
InputStream In_withcode = new Bytearrayinputstream (str.getbytes ("UTF-8"));

2.InputStream to String

Here are a few methods.

Method 1:

Public String convertstreamtostring (InputStream is) {

BufferedReader reader = new BufferedReader (new InputStreamReader (IS));

StringBuilder sb = new StringBuilder ();

String line = null;

try {

While (line = Reader.readline ()) = null) {

Sb.append (line + "/n");

}

} catch (IOException e) {

E.printstacktrace ();

} finally {

try {

Is.close ();

} catch (IOException e) {

E.printstacktrace ();

}

}

return sb.tostring ();

}

Method 2:

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

Method 3:
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 and InputStream convert each other

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.