在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分别用两个线程传送数据.
闽公网安备 35060202000074号