Conversion of string and inputstream

Source: Internet
Author: User

Inputstream provides byte stream reading instead of text reading. Reader reads char arrays or strings and inputstream reads byte arrays.

The reader class and its subclass provide the reading char of the bytes stream, and the inputstream and its subclass provide the reading byte of the byte stream. Therefore, the filereader class reads the file in the form of the bytes stream, fileinputstream reads files in byte streams. inputstreamreader can convert read data such as stream into bytes streams, which serves as a bridge between reader and stream.
1. String --> inputstream

Public inputsteam getinputstreamfromstring (string Str) {</P> <p> inputsteam in = new bytearrayinputstream (Str. getbytes (); <br/>}< br/>

 

2. inputstream --> string

Public String getstrfrominputsteam (inputsteam in) {<br/> bufferedreader BF = new bufferedreader (New inputstreamreader (in, "UTF-8 ")); <br/> // it is best to transcode the byte stream when it is switched to the bytes stream <br/> stringbuffer buffer = new stringbuffer (); <br/> string line = ""; <br/> while (line = BF. readline ())! = NULL) {<br/> buffer. append (line); <br/>}</P> <p> return buffer. tostring (); <br/>}

 

Here, of course, you can also return the string without stringbuffer, but I personally think it is better to use stringbuffer. The while loop can be used.

Ioutils. readlines (buffer). tostring ();

Related Article

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.