管道流介绍:
管道流分为管道输入流PipedInputStream和管道输出流PipedOutputStream。一般情况下,管道流使用多线程,管道输入流和管道输出流各占一个线程。
管道输入流对接管道输出流,可以在构造方法把管道输出流作为构造函数传递给管道输入流,也可以用管道流的connect(PipedOutputStream pos)方法来
进行连接。
下面是管道流的例子:
import java.io.*;
class PipedDemo
{
public static void main(String[] args) throws IOException
{
//创建管道输入流
PipedInputStream in=new PipedInputStream();
//创建管道输出流
PipedOutputStream out=new PipedOutputStream();
//管道流连接
in.connect(out);
read r=new read(in);
write w=new write(out);
new Thread(r).start();
new Thread(w).start();
}
}
//管道读取流
class read implements Runnable
{
private PipedInputStream in;
read(PipedInputStream in)
{
this.in=in;
}
public void run()
{
try
{
byte[] buf=new byte[1024];
int len=0;
while((len=in.read(buf))!=-1)
{
System.out.println(new String(buf,0,len));
}
in.close();
}
catch (IOException e)
{
throw new RuntimeException("管道读取流失败!");
}
}
}
//管道输出流
class write implements Runnable
{
private PipedOutputStream out;
write(PipedOutputStream out)
{
this.out=out;
}
public void run()
{
try
{
out.write("PipedOutputStream Come in!".getBytes());
out.close();
}
catch (IOException e)
{
throw new RuntimeException("管道输出流失败!");
}
}
}