InputStream, String, and File conversion

Source: Internet
Author: User

1. String --> InputStream
InputStream String2InputStream (String str ){
ByteArrayInputStream stream = new ByteArrayInputStream (str. getBytes ());
Return stream;
}

2. InputStream --> String
String inputStream2String (InputStream is ){
BufferedReader in = new BufferedReader (new InputStreamReader (is ));
StringBuffer buffer = new StringBuffer ();
String line = "";
While (line = in. readLine ())! = Null ){
Buffer. append (line );
}
Return buffer. toString ();
}

I saw another method on the internet today.

String all_content = null;
Try {
All_content = new String ();

InputStream ins = the obtained input stream;

ByteArrayOutputStream outputstream = new ByteArrayOutputStream ();
Byte [] str_ B = new byte [2, 1024];
Int I =-1;
While (I = ins. read (str_ B)> 0 ){
Outputstream. write (str_ B, 0, I );
}
All_content = outputstream. toString ();
} Catch (Exception e ){

E. printStackTrace ();
}

The above two methods are faster, but memory consumption is relatively high. The latter is slow and consumes less resources.

3. File --> InputStream
InputStream in = new InputStream (new FileInputStream (File ));

4. InputStream --> File
Public void inputstreamtofile (InputStream ins, File file ){
OutputStream OS = new FileOutputStream (file );
Int bytesRead = 0;
Byte [] buffer = new byte [8192];
While (bytesRead = ins. read (buffer, 0, 8192 ))! =-1 ){
OS. write (buffer, 0, bytesRead );
}
OS. close ();
Ins. close ();
}

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.