3

Possible Duplicate:
How do I convert a String to an InputStream in Java?

How can I read a String into an InputStream in Java ?

I want to be able to convert String say = "say" into an InputStream/InputSource. How do I do that?

1
  • 5
    This is pretty well documented if you just google it. Commented Jan 23, 2013 at 23:00

4 Answers 4

4
public class StringToInputStreamExample {
    public static void main(String[] args) throws IOException {
    String str = "This is a String ~ GoGoGo";

    // convert String into InputStream
    InputStream is = new ByteArrayInputStream(str.getBytes());

    // read it with BufferedReader
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }

    br.close();
   }
}

Source: How To Convert String To InputStream In Java

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Nice use of the reader :)
-1 for not specifying a Charset in str.getBytes().
3

Something like...

InputStream is = new ByteArrayInputStream(sValue.getBytes());

Should work...

Comments

0

You can use the ByteArrayInputStream. It reads elements from a byte[] with the InputStream methods.

Comments

0

For an InputStream MadProgrammer has the answer.

If a Reader is ok, then you could use:

Reader r = StringReader(say);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.