Skip to content

Instantly share code, notes, and snippets.

@NikolayGorshkov
Last active August 14, 2018 17:20
Show Gist options
  • Save NikolayGorshkov/3f08300f0e94aefa788c88a2cbfe049d to your computer and use it in GitHub Desktop.
Save NikolayGorshkov/3f08300f0e94aefa788c88a2cbfe049d to your computer and use it in GitHub Desktop.
java.nio.channels.Pipe usage example
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.URI;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse.BodyHandler;
/**
* Requires JDK 10
*
* When running the class add --add-modules=ALL-SYSTEM to JVM arguments
* to enable jdk.incubator.httpclient module
*/
public class NioPipeExample {
public static void main(String[] args) throws Exception {
Pipe pipe = Pipe.open();
Thread pipeReader = new Thread(() -> {
OutputStreamWriter out = new OutputStreamWriter(System.out, UTF_8);
try (Reader in = Channels.newReader(pipe.source(), UTF_8)) {
in.transferTo(out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
});
pipeReader.start();
try (OutputStream out = Channels.newOutputStream(pipe.sink());
InputStream in = HttpClient.newHttpClient()
.send(HttpRequest.newBuilder(new URI("https://twitter.com")).build(),
BodyHandler.asInputStream())
.body()) {
in.transferTo(out);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment