How to create an InputStream from an array of strings

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.


you can try using the class ByteArrayInputStream that you can give a byte array. But first you must convert you List to a byte array. Try the following.

    List<String> strings = new ArrayList<String>();
    strings.add("hello");
    strings.add("world");
    strings.add("and again..");

    StringBuilder sb = new StringBuilder();
    for(String s : strings){
        sb.append(s);           
    }

    ByteArrayInputStream stream = new ByteArrayInputStream( sb.toString().getBytes("UTF-8") );
    int v = -1;
    while((v=stream.read()) >=0){
        System.out.println((char)v);
    }

Tags:

Java

Java Io