Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an InputStream from an array of strings

Tags:

java

java-io

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?

like image 748
Zoltán Szőcs Avatar asked Jan 25 '12 16:01

Zoltán Szőcs


People also ask

How do you create an InputStream object?

Create an InputStream Once we import the package, here is how we can create the input stream. // Creates an InputStream InputStream object1 = new FileInputStream(); Here, we have created an input stream using FileInputStream .

Is there any method InputStream read string directly?

The readLine() method of the BufferedReader class reads a single line from the contents of the current reader. To convert an InputStream Object int to a String using this method. Instantiate an InputStreamReader class by passing your InputStream object as parameter.


2 Answers

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.

like image 195
Thomas Avatar answered Nov 10 '22 16:11

Thomas


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);
    }
like image 42
Thomas Johan Eggum Avatar answered Nov 10 '22 17:11

Thomas Johan Eggum