您的位置:首页 > 编程语言 > PHP开发

学习 PipedInputStream PipedOutputStream 改进版

2015-12-09 10:44 651 查看
package com.ftx;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class Pipe {

/**
* @author FTX
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {

PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);

new Thread(new Input(in)).start();

new Thread(new Output(out)).start();
try {
new Thread(new Output(out)).sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

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;
String s = null;
for (int i = 0; i < 5; i++) {
try {

len = in.read(buf);
if (len != -1) {
s = new String(buf, 0, len);
}

System.out.println("Input read " + s);

} catch (IOException e) {

e.printStackTrace();
}

}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

class Output implements Runnable {

@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
out.write((i + "管道流").getBytes());
out.flush();
} catch (IOException e) {

e.printStackTrace();
}

}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private PipedOutputStream out;

public Output(PipedOutputStream out) {
super();
this.out = out;
}
}


改进版,可以多个输入,读出。

博客地址 http://blog.csdn.net/ftx2540993425
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: