java中管道输入输出_管道输入输出流

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

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值