How to create an InputStream from an array of strings

Zoltán Szőcs picture Zoltán Szőcs · Jan 25, 2012 · Viewed 16.4k times · Source

I have an array of strings ( actually it's an ArrayList ) and I would like to create an InputStream from it, each element of the array being a line in the stream.

How can I do this in the easiest and most efficient way?

Answer

Thomas picture Thomas · Jan 25, 2012

You could use a StringBuilder and append all the strings to it with line breaks in between. Then create an input stream using

new ByteArrayInputStream( builder.toString().getBytes("UTF-8") );

I'm using UTF-8 here, but you might have to use a different encoding, depending on your data and requirements.

Also note that you might have to wrap that input stream in order to read the content line by line.

However, if you don't have to use an input stream just iterating over the string array would probably the easiert to code and easier to maintain solution.