I have a String[]
array and I need to convert it to InputStream
.
I've seen Byte[]
-> InputStream
and String
-> InputStream
, but not this. Any tips?
I have a String[]
array and I need to convert it to InputStream
.
I've seen Byte[]
-> InputStream
and String
-> InputStream
, but not this. Any tips?
You can construct a merged String
with some separator and then to byte[]
and then to ByteArrayInputStream
.
Here's a way to convert a String to InputStream in Java.
Have a look at the following link: http://www.mkyong.com/java/how-to-convert-string-to-inputstream-in-java/
However, the difference in the code is that you should concatenate all the strings together in one string before converting.
String concatenatedString = ... convert your array
// convert String into InputStream
InputStream is = new ByteArrayInputStream(str.getBytes());
// read it with BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
There is still no single method call to do this but with Java 8 you can do it in a single line of code. Given an array of String objects:
String[] strings = {"string1", "string2", "string3"};
You can convert the String array to an InputStream using:
InputStream inputStream = new ByteArrayInputStream(String.join(System.lineSeparator(), Arrays.asList(strings)).getBytes(StandardCharsets.UTF_8));