Java: accessing a List of Strings as an InputStream

Marc Polizzi picture Marc Polizzi · Mar 23, 2012 · Viewed 27.1k times · Source

Is there any way InputStream wrapping a list of UTF-8 String? I'd like to do something like:

InputStream in = new XyzInputStream( List<String> lines )

Answer

Dave Webb picture Dave Webb · Mar 23, 2012

You can read from a ByteArrayOutputStream and you can create your source byte[] array using a ByteArrayInputStream.

So create the array as follows:

 List<String> source = new ArrayList<String>();
 source.add("one");
 source.add("two");
 source.add("three");
 ByteArrayOutputStream baos = new ByteArrayOutputStream();

 for (String line : source) {
   baos.write(line.getBytes());
 }

 byte[] bytes = baos.toByteArray();

And reading from it is as simple as:

 InputStream in = new ByteArrayInputStream(bytes);

Alternatively, depending on what you're trying to do, a StringReader might be better.