涉及到多线程的IO流
例:
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
class Read implements Runnable
{
private PipedInputStream in;
public Read(PipedInputStream in)
{
// TODO Auto-generated constructor stub
this.in = in;
}
@Override
public void run()
{
// TODO Auto-generated method stub
byte[] buf = new byte[1024];
int len;
try
{
System.out.println("正在等待数据写入!");
len = in.read(buf);
System.out.println("已经获取到数据,正在打印!");
String s = new String(buf, 0, len);
System.out.println(s);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Write implements Runnable
{
private PipedOutputStream out;
public Write(PipedOutputStream out)
{
// TODO Auto-generated constructor stub
this.out = out;
}
@Override
public void run()
{
// TODO Auto-generated method stub
try
{
System.out.println("等待6秒中写入!");
Thread.sleep(6000);
out.write("piped data !!".getBytes());
out.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class PipedDemo
{
/**
* @param args
*/
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
pis.connect(pos);// 将输入,输出流连接在一起
Read r = new Read(pis);
Write w = new Write(pos);
new Thread(r).start();
new Thread(w).start();
}
}