Skip to content

Instantly share code, notes, and snippets.

@kamatama41
Last active January 25, 2019 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamatama41/c9df528dc38d00636584424b70c2c336 to your computer and use it in GitHub Desktop.
Save kamatama41/c9df528dc38d00636584424b70c2c336 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Spliterator;
import java.util.stream.Stream;
public class ByteArrayStreamInputStream extends InputStream {
ByteArrayStreamInputStream(Stream<byte[]> source) {
this.source = source;
this.spliterator = source.spliterator();
getNext();
}
@Override
public int read() {
if (currentInputStream == null) {
return -1; // when source stream would be empty.
}
final int ret = currentInputStream.read();
if (ret == -1) {
if (getNext()) {
// Read next bytes if exists
return read();
}
return -1;
}
return ret;
}
@Override
public void close() {
source.close();
}
private boolean getNext() {
return spliterator.tryAdvance(bytes -> currentInputStream = new ByteArrayInputStream(bytes));
}
private final java.util.stream.Stream<byte[]> source;
private final Spliterator<byte[]> spliterator;
private ByteArrayInputStream currentInputStream;
public static void main(String[] args) throws IOException {
final Stream<String> filteredStrings = Stream.of("AA", "BB", "CC")
.filter(str -> !str.contains("B"))
.map(str -> str + System.getProperty("line.separator"));
InputStream input = new ByteArrayStreamInputStream(filteredStrings.map(str -> str.getBytes(StandardCharsets.UTF_8)));
try(BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
reader.lines().forEach(System.out::println);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment