Cara Menukar OutputStream kepada InputStream
Dalam pembangunan perisian, tidak jarang anda menghadapi situasi di mana anda perlu menukar data daripada satu jenis aliran kepada yang lain. Satu senario sedemikian ialah menukar OutputStream kepada InputStream.
Pengenalan kepada Piped Streams
Penyelesaian kepada masalah ini terletak pada penggunaan kelas PipedInputStream dan PipedOutputStream Java. Kelas ini membolehkan komunikasi antara strim dengan mencipta paip dwiarah.
PipedInputStream ke OutputStream (Bukan Sebaliknya)
Ekspresi 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();
Nota: Adalah penting untuk mengendalikan situasi di mana OutputStream mungkin ditutup sebelum waktunya, yang membawa kepada ClosedPipeException. Untuk mengelakkan ini, anda boleh menyongsangkan pembina:
PipedInputStream in = new PipedInputStream(out); new Thread(() -> { originalOutputStream.writeTo(out); }).start();
Cuba-Dengan-Sumber:
// 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();
PipedOutputStream ke InputStream
Jika anda tidak mempunyai ByteArrayOutputStream, anda boleh menggunakan kod berikut:
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();
Menggunakan aliran paip menawarkan beberapa faedah, termasuk:
Atas ialah kandungan terperinci Bagaimana untuk Menukar OutputStream kepada InputStream di Java?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!