[Edit]
+
0
-
0
Java - convert OutputStream to InputStream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96// Note: in the example, InputStream waits until data is available. // ------------------------------------------------------------ // Program.java file: // ------------------------------------------------------------ import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class Program { public static void main(String[] args) throws IOException { CombinedStream combinedStream = new CombinedStream(); OutputStream outputStream = combinedStream.getOutputStream(); InputStream inputStream = combinedStream.getInputStream(); outputStream.write(new byte[] {1, 2, 3, 4, 5}); byte[] inputData = new byte[5]; // {0, 0, 0, 0, 0} int readCount = inputStream.read(inputData); // 5 // {1, 2, 3, 4, 5} } } // ------------------------------------------------------------ // CombinedStream.java file: // ------------------------------------------------------------ import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; public static class CombinedStream { private BlockingQueue<Integer> queue = new LinkedBlockingDeque<>(); private OutputStream outputStream = null; private InputStream inputStream = null; public OutputStream getOutputStream() { if (this.outputStream == null) { this.outputStream = new OutputStream() { @Override public void write(int value) throws IOException { queue.add(value); } }; } return this.outputStream; } public InputStream getInputStream() { if (this.inputStream == null) { this.inputStream = new InputStream() { @Override public int read() throws IOException { try { return queue.take(); // returns byte or waits until byte is available } catch (InterruptedException e) { throw new IOException("Input stream interrupted.", e); } } }; } return this.inputStream; } } // Hint: to read and return only available data without waiting use this source code as InputStream: /* public InputStream getInputStream() { if (this.inputStream == null) { this.inputStream = new InputStream() { @Override public int read() throws IOException { Integer value = queue.poll(); if (value == null) { return -1; } return value; } }; } return this.inputStream; } */