How to create an InputStream from an array of strings

I have an array of strings (this is actually an ArrayList) and I would like to create an InputStream from it, each element of the array will be a line in the stream.

How can I do this in the simplest and most effective way?

+5
source share
4 answers

You can use StringBuilderand add all lines to it with line breaks between them. Then create an input stream using

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

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

Also note that you may need to wrap this input stream to read the contents in turn.

, , , , .

+6

ByteArrayInputStream, . List . .

    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);
    }
+2

The simplest way would be to glue them together in a StringBuilder, and then pass the resulting String to a StringReader.

0
source

The best way is to 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) {
}
0
source

All Articles