IO流(3)之管道流类
2008-01-05 18:33:35 来源:WEB开发网在java的IO流中有一种很非凡的流就是管道流类:PipedInputStream PipedOutputStream.这两个类的实例对象必须要通过connect方法连接.
其实看这么一个程序就知道了管道流类的使用方法.
//sender.java
import java.io.*;
import java.util.*;
public class sender extends Thread
{
PipedOutputStream out = new PipedOutputStream();
public PipedOutputStream getOut()
{
return out;
}
public void run()
{
String str = "Hello,receiver ! I`m sender\n";
try
{
out.write(str.getBytes());
out.close();
}
catch(Exception e)
{
e.PRintStackTrace();
}
}
}
//receiver.java
import java.io.*;
import java.util.*;
public class receiver extends Thread
{
PipedInputStream in = new PipedInputStream();
public PipedInputStream getIn()
{
return in;
}
public void run()
{
byte [] buf = new byte[1024];
try
{
int len = in.read(buf);
System.out.println("the following is from sender:\n"+new String(buf,0,len));
in.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
//TestPiped.java
import java.io.*;
class TestPiped
{
public static void main(String [] args)
{
sender s = new sender();
receiver r = new receiver();
PipedOutputStream out = s.getOut();
PipedInputStream in = r.getIn();
try
{
in.connect(out);
s.start();
r.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
这个程序的功能是sender发送"Hello,receiver ! I`m sender"给receiver然后receiver接受后显示出来并且在前面加上"the following is from sender"的信息.要注重的就是PipedInputStream和PipedOutputStream分别用两个线程传送数据.
更多精彩
赞助商链接