Java中如何将OutputStream转换为InputStream

发布于:2025-12-25 17:4844人浏览
使用 MinIO 搭建属于自己的对象存储(OSS)

如果你曾经使用java IO编程,你会很快碰到这种情况,某个类在OutputStream上创建数据而你需要将它发送给某个需要从输入流读取数据的类。

  你很快会被问道,“java中如何将OutputStream转换为InputStream?”

  方法一:使用字节数组缓存数据

  最简单的方法是用字节数组缓存数据。代码

  ByteArrayOutputStream out = new ByteArrayOutputStream();

  class1.putDataOnOutputStream(out);

  class2.processDataFromInputStream(

  new ByteArrayInputStream(out.toByteArray())

  );

  于是,OutputStream就被转换为InputStream了。

  方法二:使用管道

  第一种方法的问题是你必须有足够的内存缓存所有数据。你可以使用文件系统缓存更多数据,但无论如何可处理数据的大小还是受到限制。

  解决方法是创建一个线程产生数据到PipedOutputStream。当前线程可从中读取数据。

  PipedInputStream in = new PipedInputStream();

  PipedOUtputStream out = new PipedOutputStream(in);

  new Thread(

  new Runnable(){

  public void run(){

  class1.putDataOnOutputStream(out);

  }

  }

  ).start();

  class2.processDataFromInputStream(in);|||

  方法三:使用循环缓存区

  方法二中的两个管道流,实际上管理着一个隐藏的循环缓存区。使用一个显式的循环缓存区更易于理解。CircularBuffers 有如下优点

  一个CircularBuffers类而不是两个管道类。

  较于缓存所有数据和额外线程的方法更容易使用。

  你可以更改缓存大小而不必受限于管道缓存区1K的固定缓存大小。

  多线程情形:

  CircularByteBuffer cbb = new CircularByteBuffer();

  new Thread(

  new Runnable(){

  public void run(){

  class1.putDataOnOutputStream(cbb.getOutputStream());

  }

  }

  ).start();

  class2.processDataFromInputStream(cbb.getInputStream());

  单线程情形

  // buffer all data in a circular buffer of infinite size

  CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);

  class1.putDataOnOutputStream(cbb.getOutputStream());

  class2.processDataFromInputStream(cbb.getInputStream());

作者“zhujianjia”

================================================

将输出流OutputStream转化为输入流InputStream的方法

一:

 

        package test.io;  

        import java.io.ByteArrayInputStream;  

        import java.io.ByteArrayOutputStream;  

        import java.io.IOException;  

        /**

         * 用于把OutputStream 转化为 InputStream。

         * 适合于数据量不大,且内存足够全部容纳这些数据的情况。

         * @author 赵学庆 www.java2000.net

         *

       */ 

      public class Test1 {  

        /**

         * @param args

         * @throws IOException

         */ 

        public static void main(String[] args) throws IOException {

          ByteArrayOutputStream out = new ByteArrayOutputStream();

          byte[] bs = new byte[] { 1, 2, 3, 4, 5 }; 

          out.write(bs);

       

          ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray())

          byte[] bs = new byte[1024];  

          int len = in.read(bs);  

          for (int i = 0; i < len; i++) {  

            System.out.println(bs[i]);  

          }  

        }

      }

 

二:

 

        package test.io;  

        import java.io.IOException;  

        import java.io.PipedInputStream;  

        import java.io.PipedOutputStream;  

        /**

         * 用于把OutputStream 转化为 InputStream。 适合于数据量大的情况,一个类专门负责产生数据,另一个类负责读取数据。

         * 

         * @author 赵学庆 www.java2000.net

         */ 

      public class Test2 {  

        /**

         * @param args

         * @throws IOException

         */ 

        public static void main(String[] args) throws IOException {  

          // 使用Piped 的输入输出流

          PipedInputStream in = new PipedInputStream();

          final PipedOutputStream out = new PipedOutputStream(in);

          // 启动线程,让数据产生者单独运行

          new Thread(new Runnable() {

            public void run() {

              try {

                       byte[] bs = new byte[2];

                       for (int i = 0; i <= 100; i++) {

                              bs[0] = (byte) i;

                      bs[1] = (byte) (i + 1);

                      // 测试写入字节数组

                     out.write(bs);

                     out.flush();

                      // 等待0.1秒

                      Thread.sleep(100);

                      }

             } catch (IOException e) {

               e.printStackTrace();

             } catch (InterruptedException e) {

                     e.printStackTrace();

               }

           }

         }).start();

         // 数据使用者处理数据

         // 也可以使用线程来进行并行处理

         byte[] bs = new byte[1024];

         int len;

         // 读取数据,并进行处理

         try {

           while ((len = in.read(bs)) != -1) {

             for (int i = 0; i < len; i++) {

               System.out.println(bs[i]);

             }

           }

         } catch (IOException e) {

           e.printStackTrace();

         }

       }

     }

 

下面是关于 PipedOutputStream 的API介绍

传送输出流可以连接到传送输入流,以创建通信管道。传送输出流是管道的发送端。通常,数据由某个线程写入 PipedOutputStream 对象,并由其他线程从连接的 PipedInputStream 读取。不建议对这两个对象尝试使用单个线程,因为这样可能会死锁该线程。

下面是关于 PipedInputStream的API介绍

传送输入流应该连接到传送输出流;传送输入流会提供要写入传送输出流的所有数据字节。通常,数据由某个线程从 PipedInputStream 对象读取,并由其他线程将其写入到相应的 PipedOutputStream。不建议对这两个对象尝试使用单个线程,因为这样可能会死锁该线程。传送输入流包含一个缓冲区,可在缓冲区限定的范围内将读操作和写操作分离开。

三:

 

         package test.io;

         import java.io.IOException;  

         import java.io.InputStream;  

         import java.io.OutputStream;  

         import com.Ostermiller.util.CircularByteBuffer;  

         /**

         * 用于把OutputStream 转化为 InputStream。

         * <p>

         * 使用CircilarBuffer 辅助类 <br>

       * 下载地址为 <A href="http://ostermiller.org/utils/download.html

      http://ostermiller.org/utils/download.html<br>

       * 介绍地址为 http://ostermiller.org/utils/CircularBuffer.html

       * </p>

       * 

       * @author 赵学庆 www.java2000.net

       */ 

      public class Test3 {  

        /**

         * @param args

         * @throws IOException

         */ 

        public static void main(String[] args) throws IOException {  

          // 使用CircularByteBuffer 

          final CircularByteBuffer cbb = new CircularByteBuffer();  

          // 启动线程,让数据产生者单独运行 

          new Thread(new Runnable() {  

            public void run() {  

              try {  

                OutputStreamClass3.putDataOnOutputStream(cbb.getOutputStream());  

              } catch (IOException e) {  

                e.printStackTrace();  

              }  

            }  

          }).start();  

          // 数据使用者处理数据 

          // 也可以使用线程来进行并行处理 

          InputStreamClass3.processDataFromInputStream(cbb.getInputStream());  

        }  

      }  

      class OutputStreamClass3 {  

        public static void putDataOnOutputStream(OutputStream out) throws IOException {  

          byte[] bs = new byte[2];  

          for (int i = 0; i <= 100; i++) {  

            bs[0] = (byte) i;  

            bs[1] = (byte) (i + 1);  

            // 测试写入字节数组 

            out.write(bs);  

            out.flush();  

            try {  

              // 等待0.1秒 

              Thread.sleep(100);  

            } catch (InterruptedException e) {  

              e.printStackTrace();   

            }  

          }  

        }  

      }  

      class InputStreamClass3 {  

        public static void processDataFromInputStream(InputStream in) {  

          byte[] bs = new byte[1024];  

          int len;  

          // 读取数据,并进行处理 

          try {  

            while ((len = in.read(bs)) != -1) {  

              for (int i = 0; i < len; i++) {  

                System.out.println(bs[i]);  

              }  

            }  

          } catch (IOException e) {  

            e.printStackTrace();  

          }  

        }  

      } 

 

此方法使用了一个类处理,代码更简洁,可以很方便的在缓冲处理全部数据的小数据量情况和多线程处理大数据量的不同情况切换

 

     package test.io;  

     import java.io.IOException;  

     import java.io.InputStream;  

     import java.io.OutputStream;  

     import com.Ostermiller.util.CircularByteBuffer;  

     /**

      * 用于把OutputStream 转化为 InputStream。

      * <p>

      * 使用CircilarBuffer 辅助类 <br>

      * 下载地址为 <A href="http://ostermiller.org/utils/download.html

     http://ostermiller.org/utils/download.html<br>

      * 介绍地址为 http://ostermiller.org/utils/CircularBuffer.html

      * </p>

      * 

      * @author 赵学庆 www.java2000.net

      */ 

     public class Test4 {  

       /**

        * @param args

        * @throws IOException

        */ 

       public static void main(String[] args) throws IOException {  

         // 缓冲所有数据的例子,不使用多线程 

         CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);  

         OutputStreamClass4.putDataOnOutputStream(cbb.getOutputStream());  

         InputStreamClass4.processDataFromInputStream(cbb.getInputStream());  

     }  

   }  

   class OutputStreamClass4 {  

     public static void putDataOnOutputStream(OutputStream out) throws IOException {  

       byte[] bs = new byte[] { 1, 2, 3, 4, 5 };  

       out.write(bs);  

     }  

   }  

   class InputStreamClass4 {  

     public static void processDataFromInputStream(InputStream in) throws IOException {  

       byte[] bs = new byte[1024];  

       int len = in.read(bs);  

       for (int i = 0; i < len; i++) {  

         System.out.println(bs[i]);  

       }  

     }  

   } 


相关文章
    最新文章
    热门标签