Skip to content

Instantly share code, notes, and snippets.

@darkjh
Created September 4, 2016 23:33
Show Gist options
  • Save darkjh/cfe96c8942838d962db9cf33cef25d85 to your computer and use it in GitHub Desktop.
Save darkjh/cfe96c8942838d962db9cf33cef25d85 to your computer and use it in GitHub Desktop.
OutputStream to InputStream
import java.io.OutputStreamWriter
import java.io.{PipedInputStream, PipedOutputStream, ByteArrayOutputStream, PrintStream}
import java.io.{BufferedReader, InputStreamReader}
import org.apache.commons.io.output.TeeOutputStream
import scala.{App => SApp}
object TestOut extends SApp {
val orig = System.out
val in = new PipedInputStream()
val out = new PipedOutputStream(in)
val tee = new TeeOutputStream(orig, out)
System.setOut(new PrintStream(tee))
new Thread(new Runnable {
val reader = new BufferedReader(new InputStreamReader(in))
override def run(): Unit = {
var line: String = null
while ({
line = reader.readLine()
line != null
}) {
System.err.println(s">> $line")
}
}
}).start()
Thread.sleep(1000)
while (true) {
System.out.println("abc")
Thread.sleep(1000)
}
}
object TestPipe extends SApp {
val in = new PipedInputStream()
val out = new PipedOutputStream(in)
new Thread(new Runnable {
val w = new OutputStreamWriter(out)
override def run(): Unit = {
while (true) {
w.write("abc\n")
w.flush()
Thread.sleep(1000)
}
}
}).start()
val reader = new BufferedReader(new InputStreamReader(in))
var line: String = null
while ({
line = reader.readLine()
line != null
}) {
println(line)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment