管道流类 PipedOutputStream 与 PipInputStream 相连 用于线程之间传输数据
让程序中多个模块的输入与输出流相连
write之后如果不调用flush()可能会报错
windows ctrl+z 结束 linux ctrl+d 为键盘结束标记
键盘输入 System.in 显示其输出System.out 输入输出流的具体实例
******************************************************************************
* 将常用的功能封装成为函数提高程序的复用性,输入的结束点设置为-1,函数使用父类,传递直接传递子类对象。*
******************************************************************************
测试结果
****************************************
这次的i是:1
**!**!**!**
这次的i是:2
**!**!**!**
这次的i是:3
**!**!**!**
这次的i是:4
**!**!**!**
这次的i是:5
**!**!**!**
这次的i是:6
**!**!**!**
这次的i是:7
**!**!**!**
这次的i是:8
**!**!**!**
这次的i是:9
**!**!**!**
这次的i是:10
**!**!**!**
******************************************
代码
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class Piped {
public static void main(String[] args){
Getter g1 = new Getter();
Sender s1 = new Sender();
PipedInputStream in = g1.getin();
PipedOutputStream out = s1.getOut();
try {
out.connect(in);
} catch (IOException e) {
e.printStackTrace();
}
g1.start();
s1.start();
}
}
class Sender extends Thread {
PipedOutputStream out = new PipedOutputStream();
public PipedOutputStream getOut(){
return out;
}
public void run(){
int i = 0;
String str = "";
while (i<10){
i++;
str = "这次的i是:"+i;
try {
out.write(str.getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
out.write("stop".getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Getter extends Thread {
PipedInputStream in = new PipedInputStream();
public PipedInputStream getin(){
return in;
}
public void run(){
String str = "";
int len;
byte[] b = new byte[1024];
int i= 0;
while (i==0){
try {
len = in.read(b);
str="";
str = new String(b,0,len);
if(str.equals("stop")){
break;
}
System.out.println(str);
System.out.println("**!**!**!**");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteArrayTest {
public static void main(String[] args) {
String str = "abcdefghijklmnopqrstuvwxyz";
byte[] b = str.getBytes();
ByteArrayInputStream bais= new ByteArrayInputStream(b);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transform(bais,baos);
byte[] re = baos.toByteArray();
String strre = new String(re);
System.out.println(strre);
transform(System.in,System.out);
}
public static void transform(InputStream in,OutputStream out){
int ch = 0;
int cont = 0;
try {
while((ch=in.read()) != -1){
cont++;
int upperCh = (int)Character.toUpperCase((char)ch);
out.write(upperCh);
}
} catch (IOException e) {
e.printStackTrace();
}
}