1

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
  • 60,548
  • 8
  • 97
  • 143
Walrus the Cat
  • 2,172
  • 5
  • 33
  • 61

3 Answers3

5

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
  • 232,312
  • 42
  • 391
  • 431
  • 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

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,023
  • 1
  • 27
  • 34
2

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
  • 22,383
  • 14
  • 83
  • 147