如何將OutputStream 轉換為InputStream
在軟體開發中,常常會遇到需要將資料從一個串流轉換為一個串流的情況。流類型到另一個。其中一個場景是將 OutputStream 轉換為 InputStream。
管道流簡介
這個問題的解決方案在於使用 Java 的 PipedInputStream 和 PipedOutputStream 類別。這些類別透過創建雙向管道來實現流之間的通訊。
PipedInputStream 到OutputStream(反之亦然)
Lambda 表達式:
PipedInputStream in = new PipedInputStream(); final PipedOutputStream out = new PipedOutputStream(in); // in a background thread, write the given output stream to the PipedOutputStream for consumption new Thread(() -> { originalOutputStream.writeTo(out); }).start();
必須處理OutputStream 可能過早關閉的情況,從而導致ClosedPipeException。為了避免這種情況,您可以反轉建構子:
PipedInputStream in = new PipedInputStream(out); new Thread(() -> { originalOutputStream.writeTo(out); }).start();
Try-With-Resources:
// take the copy of the stream and re-write it to an InputStream PipedInputStream in = new PipedInputStream(); new Thread(new Runnable() { public void run() { // try-with-resources here // putting the try block outside the Thread will cause the PipedOutputStream resource to close before the Runnable finishes try (final PipedOutputStream out = new PipedOutputStream(in)) { // write the original OutputStream to the PipedOutputStream // note that in order for the below method to work, you need to ensure that the data has finished writing to the ByteArrayOutputStream originalByteArrayOutputStream.writeTo(out); } catch (IOException e) { // logging and exception handling should go here } } }).start();
PipedputStream 到InputStream 到🎜>
如果您沒有ByteArrayOutputStream,可以使用以下程式碼:PipedInputStream in = new PipedInputStream(); final PipedOutputStream out = new PipedOutputStream(in); new Thread(new Runnable() { public void run() { try { // write the original OutputStream to the PipedOutputStream // note that in order for the below method to work, you need to ensure that the data has finished writing to the OutputStream originalOutputStream.writeTo(out); } catch (IOException e) { // logging and exception handling should go here } finally { // close the PipedOutputStream here because we're done writing data // once this thread has completed its run if (out != null) { // close the PipedOutputStream cleanly out.close(); } } } }).start();
以上是Java中如何將OutputStream轉換為InputStream?的詳細內容。更多資訊請關注PHP中文網其他相關文章!