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?

3
  • 1
    An InputStream of what? Delimited? Length-prefixed? Commented Sep 22, 2013 at 23:30
  • 1
    An InputStream is for binary, perhaps you wanted a Reader which is for text? Commented Sep 22, 2013 at 23:31
  • Actually, either will do, but I arbitrarily chose to ask about InputStream. Commented Sep 22, 2013 at 23:34

3 Answers 3

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.

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

1 Comment

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.
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();

Comments

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.