【java编程】IO流之管道流

管道流介绍:

管道流分为管道输入流PipedInputStream和管道输出流PipedOutputStream。一般情况下,管道流使用多线程,管道输入流和管道输出流各占一个线程。

管道输入流对接管道输出流,可以在构造方法把管道输出流作为构造函数传递给管道输入流,也可以用管道流的connect(PipedOutputStream pos)方法来

进行连接。

下面是管道流的例子:

import java.io.*;
class PipedDemo 
{
	public static void main(String[] args)  throws IOException
	{
		//创建管道输入流
		PipedInputStream in=new PipedInputStream();
		//创建管道输出流
		PipedOutputStream out=new PipedOutputStream();
		//管道流连接
		in.connect(out);		
		read r=new read(in);
		write w=new write(out);
		new Thread(r).start();
		new Thread(w).start();
	}
}
//管道读取流
class read implements Runnable
{
	private PipedInputStream in;
	read(PipedInputStream in)
	{
		this.in=in;
	}
	public void run()
	{
		try
		{
			byte[] buf=new byte[1024];
			int len=0;
			while((len=in.read(buf))!=-1)
			{
				System.out.println(new String(buf,0,len));
			}
			in.close();
		}
		catch (IOException e)
		{
			throw new RuntimeException("管道读取流失败!");
		}
	}
}
//管道输出流
class write implements Runnable
{
	private PipedOutputStream out;
	write(PipedOutputStream out)
	{
		this.out=out;
	}
	public void run()
	{
		try
		{
			out.write("PipedOutputStream Come in!".getBytes());
			out.close();
		}
		catch (IOException e)
		{
			throw new RuntimeException("管道输出流失败!");
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值