import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import javax.swing.tree.FixedHeightLayoutCache;
//管道输入输出流:将源文件的内容通过管道送到目的文件-有6个基本类,源文件类,目的文件类,读管道,写管道,读线程,写线程。
//源文件读取自己的数据
//读线程获得源文件读取的数据,打印且写管道将其写入管道中。
//读管道读取管道中的数据,目的文件将其写入目的文件中。
public class demo3 {
/**
* @param args
*/
demo3()
{
try {
String readPathString="E:\test.txt";
String writePathString="E:\out4.txt";
PipedOutputStream p1=new PipedOutputStream();
PipedInputStream p2=new PipedInputStream();
p1.connect(p2);
Sender sender1=new Sender(readPathString, p1);
Receiver receiver1=new Receiver(writePathString, p2);
sender1.start();
receiver1.start();
} catch (Exception e) {
System.out.print(e.getMessage());
e.printStackTrace();// TODO: handle exception
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
demo3 a=new demo3();
}
}
//读线程,源地址
class Sender extends Thread
{
String readPathString;
PipedOutputStream p1;
Sender(String readPathString,PipedOutputStream p1)
{
this.readPathString=readPathString;
this.p1=p1;
}
public void run() {
try
{
FileInputStream fis=new FileInputStream(readPathString);
int data=fis.read();
while(data!=-1)
{
Thread.sleep(5);
System.out.print((char)data);
p1.write(data);
data=fis.read();
}
fis.close();
p1.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
//写线程,目的地址
class Receiver extends Thread
{
String writePath;
PipedInputStream p2=new PipedInputStream();
public Receiver(String writePath,PipedInputStream p2)
{
this.writePath=writePath;
this.p2=p2;
}
public void run()
{
try
{
FileOutputStream pos=new FileOutputStream(writePath);
int data=p2.read();
while(data!=-1)
{
Thread.sleep(5);
System.out.print((char)data);
pos.write(data);
data=p2.read();
}
p2.close();
pos.close();
}
catch (Exception e)
{
System.out.print(e.getMessage());
e.printStackTrace();// TODO: handle exception
}
}
}