How to create an InputStream from an array of strings
Asked Answered
U

5

8

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?

Unfrock answered 25/1, 2012 at 16:11 Comment(1)
I'm getting the array from a callback, and want to add it to a zip file as a ZipEntity (therefore the InputStream). I also thought of the StringBuilder method, but I hoped there would be some nicer ( some InputStream wrapper ) way to do it...Arthur
C
10

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.

Cwmbran answered 25/1, 2012 at 16:18 Comment(0)
D
4

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);
    }
December answered 25/1, 2012 at 16:39 Comment(0)
E
0

The easiest might be to glue them together in a StringBuilder and then pass the resultant String to StringReader.

Evita answered 25/1, 2012 at 16:18 Comment(0)
F
0

The better way is use the BufferedWriter class. There is one sample:

try {
    List<String> list = new ArrayList<String>();
    BufferedWriter bf = new BufferedWriter(new FileWriter("myFile.txt"));

    for (String string : list) {
        bf.write(string);
        bf.newLine();
    }

    bf.close();
} catch (IOException ex) {
}
Fraud answered 25/1, 2012 at 16:24 Comment(0)
P
0

I am doing this since you can skip some copying and hence garbage vs the StringBuilder approach.

    public InputStream createInputStream(String ... strings){
        List<ByteArrayInputStream> streams = new ArrayList<>();
        for(String string: strings){
            streams.add(new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)));
        }
        return new SequenceInputStream(Collections.enumeration(streams));
    }
Postmistress answered 17/2, 2021 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.