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