PipedInputStream与PipedOutputStream类用于在应用程序中的创建管道通信
主要用于完成线程间的通信
管道要能通信必须要建立连接connect
public class Sender extends Thread
{
private PipedOutputStream out = new PipedOutputStream();
public PipedOutputStream getOutputStream()
{
return out;
}
public void run()
{
String strInfo = new String("hello,receiver!");
try
{
out.write(strInfo.getBytes());
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public class Receiver extends Thread
{
private PipedInputStream in = new PipedInputStream();
public PipedInputStream getInputStream()
{
return in;
}
public void run()
{
bytep[] buf = new byte[1024];
try
{
int len = in.read(buf);
System.out.println("the following message comes from sender:/n" + new String(buf,0,len));
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception
{
Sender t1 = new Sender();
Receiver t2 = new Receiver();
PipedOutputStream out = t1.getOutputStream();
PipedInputStream in = t2.getInputStream();
out.connect(in);
t1.start();
t2.start();
}
PipedWriter和PipedReader类
使用管道流类,可以实现各个程序模块之间的松耦合通信。
使用管道流,有利于模块化
ByteArrayInputStream与ByteArrayOutputStream类
ByteArrayInputStream与ByteArrayOutputStream,用于以IO流的方式来完成对字节数组内容
的读写,来支持类似内存虚拟文件或者内存映像文件的功能。
ByteArrayInputStream的两个构造函数
-ByteArrayInputStream(byte[] buf)
-ByteArrayInputStream(byte[] buf,int offset,int length)
ByteArrayOutputStream
-ByteArrayOutputStream() //创建32个字节的缓冲区,数据过大或自动增长
-ByteArrayOutputStream(int)//创建指定大小的缓冲区,数据过大或自动增长
public static void main(String[] args)
{
String tmp = "abcde";
byte[] src = tmp.getBytes();
ByteArrayInputStream input = new ByteArrayInputStream(src);
ByteArrayOutputStream output = new ByteArrayOutputStream();
transform(input,output);
byte[] result = output.toByteArray();
System.out.println(new String(result));
transform(System.in,System.out);//复用性,读取键盘输入然后从屏幕输出
}
public static void transform(InputStream in,OutputStream out)
{
int ch = 0;
try
{
while(ch = in.read() != -1)
{
int upperCh = /*(int)*/Character.toUpperCase( (char)ch );
out.write(upperCh);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
StringReader和StringWriter类来以字符IO流的方式处理字符串
重视IO程序代码的复用
-System.in连接到键盘,是InputStream类型的实例对象。
-System.out连接到显示器,是PrintStream类的实例对象。
-不管各种底层物理设备用什么方式实现数据的终止点,InputStream的
read方式总是返回-1来表示输入流的结束。
-在Windows下,按下Ctrl+Z组合键可以产生键盘输入流的结束标记,在
Linux下,则是按下Ctrl+D组合键来产生键盘输入流的结束标记。