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?

Community
  • 1
  • 1
Phoenix
  • 8,357
  • 16
  • 51
  • 84

4 Answers4

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

animuson
  • 52,378
  • 28
  • 138
  • 145
MikeB
  • 2,382
  • 1
  • 13
  • 24
2

Something like...

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

Should work...

MadProgrammer
  • 336,120
  • 22
  • 219
  • 344
0

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

SJuan76
  • 24,098
  • 6
  • 44
  • 83
0

For an InputStream MadProgrammer has the answer.

If a Reader is ok, then you could use:

Reader r = StringReader(say);
xagyg
  • 9,304
  • 2
  • 29
  • 28