简介
PipedInputStream和PipedOutputStream是一对输入输出,这里需要明白的是,PipedOutPutStream和PipedInputStream必须相连,而且,前者的读取必须要等待后者的写入后才能够执行
除此之外,这两者要结合线程来使用
案例
用一个读者和写者,来模拟两者的写入读出
public class Writer implements Runnable{
PipedOutputStream pos=null;
Writer(PipedOutputStream pos)
{
this.pos=pos;
}
public void write() {
}
@Override
public void run() {
System.out.println("我要停3秒");
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String msg="写一条信息进去";
try {
pos.write(msg.getBytes());
pos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Reader implements Runnable{
PipedInputStream pis=null;
Reader(PipedInputStream pis)
{
this.pis=pis;
}
@Override
public void run() {
StringBuilder sb=new StringBuilder();
int len=0;
byte[] b=new byte[1024];
try {
while((len=pis.read(b))!=-1)
{
sb.append(new String(b,0,len));
}
System.out.println(sb.toString());
pis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class IOMain {
public static void main(String[] args) throws Exception{
PipedTest();
}
public static void PipedTest() throws Exception{
PipedInputStream pis=null;
PipedOutputStream pos=null;
pis=new PipedInputStream();
pos=new PipedOutputStream(pis);
Thread t1=new Thread(new Writer(pos));
Thread t2=new Thread(new Reader(pis));
t1.start();
t2.start();
//pis.close();
//pos.close();
}
public static void sop(Object o)
{
System.out.println(o);
}
}
总结
这里别忘记给两者相连接,这一对输入输出流并没有什么难点,只是说需要结合线程来使用