论坛首页 入门技术论坛

java IO管道流

浏览 1322 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-05-26  
package com.io.file;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;


/**
 * @类功能说明:管道流
 * @类修改者:
 * @修改日期:
 * @修改说明:
 * @作者:matieli
 * @创建时间:May 26, 2012 9:56:29 AM
 * @版本:V1.0
 *
 */
class Read implements Runnable {
	private PipedInputStream in;

	public Read(PipedInputStream in) {
		this.in = in;
	}

	public void run() {
		try {
			
			byte[] b = new byte[1024];
			System.out.println("读取前,没有数据就阻塞");
			int len = in.read(b);
			System.out.println("读到数据,阻塞结束");
			String s = new String(b, 0, len);
			System.out.println(s);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

class Write implements Runnable {
	private PipedOutputStream out;

	public Write(PipedOutputStream out) {
		this.out = out;
	}

	public void run() {
		try {
			System.out.println("开始写入数据,等待5秒");
			Thread.sleep(5000);
			out.write("管道流来了".getBytes());
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

public class PipedStreamDemo {
	public static void main(String[] args)throws Exception {
		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();
	}
}

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics