输出管道对象调用write()成员函数输出数据(即向管道的输入端发送数据)
输入管道对象调用read()成员函数可以赌气数据(即向管道的输入端获取数据)
1.1 线程继承实现 extends thread
package org.io;
import java.io.*;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* 管道流
* @author 我的账号
* 输出管道对象调用write()成员函数输出数据(即向管道的输入端发送数据)
* 输入管道对象调用read()成员函数可以赌气数据(即向管道的输入端获取数据)
*/
public class PipeStream {
public static void main(String[] args) {
try {
//构造读写的管道流对象
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
//实现关联
pos.connect(pis);
//构造两个线程,并且启动
new Sender(pos, "D:\\text2.txt").start();
new Receiver(pis, "d:\\text3.txt").start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//sender 线程
class Sender extends Thread{
PipedOutputStream pos;
File file;
//构造方法
Sender(PipedOutputStream pos,String fileName){
this.pos = pos;
file = new File(fileName);
}
char ch;
//线程运行方法
public void run(){
try {
//读文件内容
FileInputStream fs = new FileInputStream(file);
int data;
while((data = fs.read()) != -1){
//写入管道始端
pos.write(data);
}
pos.close();
} catch (Exception e) {
System.out.println("send error" + e);
}
}
}
//receiver 线程
class Receiver extends Thread{
PipedInputStream pis;
File file;
//构造方法
Receiver(PipedInputStream pis,String filename){
this.pis = pis;
file = new File(filename);
}
//线程运行
public void run(){
try {
//写文件流对象
FileOutputStream fos = new FileOutputStream(file);
int data;
//从管道末端读
while((data = pis.read()) != -1){
//写入本地文件
fos.write(data);
}
} catch (Exception e) {
System.out.println("receiver Error"+e);
}
}
}1.2 实现线程 implements runnable
package org.io;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* 管道流
* @author 我的账号
*
*/
public class PipeStream2 {
public static void main(String[] args) throws Exception{
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
//将两个管道流链接起来
pis.connect(pos);
//多线程交互使用
new Thread(new Input(pis)).start();
new Thread(new output(pos)).start();
}
}
//输入部分
class Input implements Runnable{
private PipedInputStream in;
public Input(PipedInputStream in){
super();
this.in = in;
}
@Override
public void run() {
byte[] buf = new byte[1024];
int len;
try{
len = in.read(buf);
String s = new String(buf,0,len);
System.out.println("输出管道数据: "+s);
in.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
//输出部分
class output implements Runnable{
private PipedOutputStream out;
public output(PipedOutputStream out){
super();
this.out = out;
}
@Override
public void run() {
try {
out.write("源管道流".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
}