2

I have a String[] array and I need to convert it to InputStream.

I've seen Byte[] -> InputStream and String -> InputStream, but not this. Any tips?

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
Walrus the Cat
  • 2,314
  • 5
  • 35
  • 64

3 Answers3

6

You can construct a merged String with some separator and then to byte[] and then to ByteArrayInputStream.

Here's a way to convert a String to InputStream in Java.

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • Yeah... that's the way I was going to go... zip up an array of newlines with my string array and join to a string... but I was hoping there was a more direct route. – Walrus the Cat Sep 22 '13 at 23:34
3

Have a look at the following link: http://www.mkyong.com/java/how-to-convert-string-to-inputstream-in-java/

However, the difference in the code is that you should concatenate all the strings together in one string before converting.

 String concatenatedString = ... convert your array

        // 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();
Menelaos
  • 23,508
  • 18
  • 90
  • 155
3

There is still no single method call to do this but with Java 8 you can do it in a single line of code. Given an array of String objects:

    String[] strings = {"string1", "string2", "string3"};

You can convert the String array to an InputStream using:

    InputStream inputStream = new ByteArrayInputStream(String.join(System.lineSeparator(), Arrays.asList(strings)).getBytes(StandardCharsets.UTF_8));
Chase
  • 3,123
  • 1
  • 30
  • 35