5 PipedInputStream 类和PipedOutputStream类用于在程序中创建管道通信
PipedWriter PipedReader 用于字符串管道流
使用管道流类可以实现各个程序模块之间的松耦合通信。
强内聚,弱耦合。
举例说明:
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;/**
* 管道通信流类demo
* @author zhbb
*
*/
public class DemoPipedStream
{/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
Sender s1 = new Sender();
Receiver r1 = new Receiver();
PipedOutputStream out = s1.getOutputStream();
PipedInputStream in = r1.getInputStream();
try
{
//连接in管道流
out.connect(in);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//启动线程
s1.start();
r1.start();
}}
//发送者
class Sender extends Thread
{
private PipedOutputStream pout = new PipedOutputStream();
public PipedOutputStream getOutputStream()
{
return pout;
}
public void run()
{
String strInfo = new String("我是一名老师……");
try
{
System.out.println("向管道写入数据:");
pout.write(strInfo.getBytes());
pout.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}//接受者
class Receiver extends Thread
{
private PipedInputStream pin = new PipedInputStream();
public PipedInputStream getInputStream()
{
return pin;
}
public void run()
{
try
{
byte[] buf = new byte[1024];
int len = pin.read(buf);
pin.close();
System.out.println("从管道中收到的信息:\n" + new String(buf,0,len));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
6 ByteArrayInputStream ByteArrayOutputStream
用于以IO流的方式来完成对字节数组内容的读写,来支持类似内存虚拟文件或者内存映像文件的功能
ByteArrayInputStream(byte[] buf)
ByteArrayInputStream(byte[] buf,int offset,int length)
ByteArrayOutputStream()
ByteArrayOutputStream(int)
StringReader StringWriter 用于处理字符串的IO流
举例说明:
/**
* 数组流,模拟字符串小写转大写 并可以从键盘上输入字符,回显大写字符。
* @author zhbb
*
*/
public class DemoByteArrayStream
{
public static void main(String[] args) throws Exception
{
String tmp = "abckddfkkmnloprstwyz";
byte[] buf = tmp.getBytes();
ByteArrayInputStream baIn = new ByteArrayInputStream(buf);
ByteArrayOutputStream baOut = new ByteArrayOutputStream();
transform(baIn,baOut);
byte[] result = baOut.toByteArray();
System.out.println(new String(result));
//将键盘输入的字符转换成大写的字符
transform(System.in,System.out);
}
//字符小写转大写
public static void transform(InputStream in,OutputStream out)
{
try
{
int ch = 0;
while((ch = in.read()) != -1)
{
int upperCh = (int)Character.toUpperCase((char)ch);
out.write(upperCh);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
7 附件知识
System.out 连接到显示器 是PrintStream实例对象
System.in 连接到键盘 是InputStream实例对象
不管各种底层物理设备用什么方式实现数据的终止点,InputStream的read方法总是返回-1 表示输入流的结束。
在Windows下,按下Ctrl+Z键可以产生键盘输入流的结束标记,在linux下使用Ctrl+D键
其他IO流的介绍待续。