首頁  >  文章  >  Java  >  Java中如何將OutputStream轉換為InputStream?

Java中如何將OutputStream轉換為InputStream?

Linda Hamilton
Linda Hamilton原創
2024-11-09 04:11:02162瀏覽

How to Convert an OutputStream to an InputStream in Java?

如何將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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn