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