String and InputStream are converted to each other

Source: Internet
Author: User
Tags stringbuffer

1.String to InputStream

String str = "string and InputStream are converted to each other";

InputStream in = new Bytearrayinputstream (Str.getbytes ());


InputStream in = new Bytearrayinputstream (str.getbytes ("UTF-8"));

It is recommended that this method be used to specify that code is not easy to garbled.

2.InputStream to String

Here are a few ways to do this.

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

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.