由於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)