
net.dongliu.cute.http.body.AggregateInputStream Maven / Gradle / Ivy
The newest version!
package net.dongliu.cute.http.body;
import net.dongliu.commons.io.Closeables;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* InputStream that merge multi InputStreams.
*/
class AggregateInputStream extends InputStream {
private InputStream[] inputStreams;
private int index;
public AggregateInputStream(InputStream... inputStreams) {
this.inputStreams = inputStreams;
}
public AggregateInputStream(List inputStreams) {
this.inputStreams = inputStreams.toArray(InputStream[]::new);
}
@Override
public synchronized int read(byte[] b) throws IOException {
if (EOF()) {
return -1;
}
do {
int count;
if ((count = current().read(b)) >= 0) {
return count;
}
} while (next());
return -1;
}
@Override
public synchronized int read(byte[] b, int off, int len) throws IOException {
if (EOF()) {
return -1;
}
do {
int count;
if ((count = current().read(b, off, len)) >= 0) {
return count;
}
} while (next());
return -1;
}
@Override
public synchronized long skip(long n) throws IOException {
if (EOF()) {
return 0;
}
return current().skip(n);
}
@Override
public synchronized int available() throws IOException {
if (EOF()) {
return 0;
}
return current().available();
}
@Override
public synchronized int read() throws IOException {
if (EOF()) {
return -1;
}
do {
int value;
if ((value = current().read()) >= 0) {
return value;
}
} while (next());
return -1;
}
@Override
public synchronized void close() throws IOException {
for (var in : inputStreams) {
Closeables.closeQuietly(in);
}
}
/*
* Delegate to next inputStream.
* return false if no more stream
*/
private boolean next() {
if (index >= inputStreams.length - 1) {
return false;
}
Closeables.closeQuietly(inputStreams[index]);
index++;
return true;
}
/*
* Current inputStream delegated to .
*/
private InputStream current() {
return inputStreams[index];
}
private boolean EOF() {
return index >= inputStreams.length;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy