How to convert String to InputStream?

H

Harald Hein

Ahmed Moustafa said:
Is there a way to convert String to InputStream?

By reading the API documentation you could have found:

(a) The deprecated StringBufferInputStream.

Deprecated because it is not a good idea to read the characters in a
string as bytes with unspecified encoding.

(b) ByteArrayInputStream(theString.getBytes())

Using the platforms encoding.

(c) ByteArrayInputStream(theString.getBytes("encodingName"))

Using the specified encoding.
Thanks in advance,

Please read the API documentation in advance.
 
C

Chris Smith

Ahmed said:
Is there a way to convert String to InputStream?

Sure.

public static final String ENCODING = ...;

public static InputStream fromString(String str)
{
byte[] bytes = str.getBytes(ENCODING);
return new ByteArrayInputStream(bytes);
}

You have to choose an appropriate encoding, though. Unfortunately, this
requires that you do the whole encoding of the text at once. It
shouldn't be difficult to write an InputStream that provides the
encoding on smaller chunks iteratively, if you expect to be working with
very large Strings. If you need help doing so, let me know.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
C

Chris Smith

Chris said:
You have to choose an appropriate encoding, though. Unfortunately, this
requires that you do the whole encoding of the text at once. It
shouldn't be difficult to write an InputStream that provides the
encoding on smaller chunks iteratively, if you expect to be working with
very large Strings. If you need help doing so, let me know.

I should clarify that I meant let me know on the newsgroup. Anyone who
wants a snowball's chance in hell of my seeing their message should not
send it to me by email at the moment.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
A

Ahmed Moustafa

Is there a way to convert String to InputStream?
By reading the API documentation you could have found:

(a) The deprecated StringBufferInputStream.

I had already known about it and was trying to avoid it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top