Is there any way InputStream
wrapping a list of UTF-8 String
? I\'d like to do something like:
InputStream in = new XyzInputStream( List
You can create some kind of IterableInputStream
public class IterableInputStream extends InputStream {
public static final int EOF = -1;
private static final InputStream EOF_IS = new InputStream() {
@Override public int read() throws IOException {
return EOF;
}
};
private final Iterator iterator;
private final Function mapper;
private InputStream current;
public IterableInputStream(Iterable iterable, Function mapper) {
this.iterator = iterable.iterator();
this.mapper = mapper;
next();
}
@Override
public int read() throws IOException {
int n = current.read();
while (n == EOF && current != EOF_IS) {
next();
n = current.read();
}
return n;
}
private void next() {
current = iterator.hasNext()
? new ByteArrayInputStream(mapper.apply(iterator.next()))
: EOF_IS;
}
}
To use it
public static void main(String[] args) throws IOException {
Iterable strings = Arrays.asList("1", "22", "333", "4444");
try (InputStream is = new IterableInputStream(strings, String::getBytes)) {
for (int b = is.read(); b != -1; b = is.read()) {
System.out.print((char) b);
}
}
}