Skip to content

Commit 3e0ec70

Browse files
committed
pipe
1 parent e4d6bf6 commit 3e0ec70

1 file changed

Lines changed: 92 additions & 0 deletions

File tree

IO/code/PipeStream.java

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package com.example.iostream;
2+
3+
import java.io.IOException;
4+
import java.io.PipedInputStream;
5+
import java.io.PipedOutputStream;
6+
import java.text.SimpleDateFormat;
7+
import java.util.Date;
8+
9+
/**
10+
* Created by guolei on 16-8-5.
11+
* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
12+
* | 没有神兽,风骚依旧! |
13+
* | QQ:1120832563 |
14+
* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
15+
*/
16+
17+
18+
public class PipeStream {
19+
//http://xouou.iteye.com/blog/1333475
20+
public static void main(String[] args){
21+
PipedInputStream pis = new PipedInputStream();
22+
PipedOutputStream pos = new PipedOutputStream();
23+
24+
try {
25+
pis.connect(pos);
26+
} catch (IOException e) {
27+
e.printStackTrace();
28+
}
29+
30+
new Thread(new ReadThread(pis)).start();
31+
new Thread(new WriteThread(pos)).start();
32+
}
33+
34+
static class ReadThread implements Runnable{
35+
36+
private PipedInputStream pis ;
37+
38+
public ReadThread(PipedInputStream pis){
39+
this.pis = pis ;
40+
}
41+
42+
@Override
43+
public void run() {
44+
byte[] b = new byte[1024];
45+
try {
46+
if (null != pis){
47+
System.err.println(getDate() + " 等待另一头输入数据");
48+
while (pis.read(b) != -1){
49+
System.err.println(getDate()+ " 读取成功,数据为:"+new String(b).trim());
50+
}
51+
pis.close();
52+
}else {
53+
System.err.println("pis is null");
54+
}
55+
} catch (IOException e) {
56+
e.printStackTrace();
57+
}
58+
}
59+
}
60+
61+
static class WriteThread implements Runnable{
62+
63+
private PipedOutputStream pos;
64+
65+
public WriteThread(PipedOutputStream pos){
66+
this.pos = pos ;
67+
}
68+
69+
@Override
70+
public void run() {
71+
byte[] b = new byte[1024];
72+
try {
73+
if (null != pos){
74+
Thread.sleep(5000);
75+
pos.write("这是输入的数据".getBytes("utf-8"));
76+
System.err.println(getDate()+" 输入数据成功");
77+
pos.close();
78+
}
79+
}catch (IOException e){
80+
e.printStackTrace();
81+
} catch (InterruptedException e) {
82+
e.printStackTrace();
83+
}
84+
}
85+
}
86+
87+
private static String getDate(){
88+
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
89+
90+
return simpleDateFormat.format(new Date().getTime());
91+
}
92+
}

0 commit comments

Comments
 (0)