java管道使用

        由於java語言的stream嚴格區分爲inputstream和outputstream,流數據讀寫之間轉換一般使用臨時文件方式來轉換。但是這種方式使用的效率比較低,因此可以使用管道來實現。

       java管道支持比較弱,需要多線程來支持,例如: 

      

import java.io.*;
class Read implements Runnable
{
        private PipedInputStream in;
        Read(PipedInputStream in)
        {
                this.in = in;
        }
        public  void run()
        {
                try
                {
                        byte[] buf = new byte[1024];
                        int len = in.read(buf);
                        String s = new String(buf,0,len);
                        System.out.println(s);
                        in.close();
                }
                catch(IOException e)
                {
                        throw new RuntimeException("read failed");
                }
        }
}
class Write implements Runnable
{
        private PipedOutputStream out;
        Write(PipedOutputStream out)
        {
                this.out. = out ;
        
        }
        public void run()
        {
                try
                {
                        out.write("piped  come here"),getBytes());
                        out.close();
                }
                catch(IOException e)
                {
                        throw new RuntimeException("piped out failed");
                }
        }
}
class PipedStreamDemo
{
        public static void main(String[] args) throws IOException
        {
                PipedInputStream in = new PipedInputStream();
                PipedOutputStream out = new PipedOutputStream();
                in.connect(out);
                Read r = new Read();
                Write w = new Write();
                Thread t1 = new Thread(r);
                Thread t2 = new Thread(w);
                t1.start();
                t2.start();
                
        }
}


    由於jdk6之前版本支持1024爲pipesize,之後的版本可以支持定製pipesize,調用方式爲:PipedInputStream(int pipeSize)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章