JAVA IO - 管道

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipedInputStreamTest {
	public static void main(String args[]) {
		PipedInputStream input = new PipedInputStream();
		PipedOutputStream output = new PipedOutputStream();
		try {
			
			output.connect(input);
//			input.connect(output);
			new Thread(new OutputstreamRunnable(output)).start();
//			Thread.sleep(1000);
			new Thread(new InputstreamRunnable(input)).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class OutputstreamRunnable implements Runnable {

	private OutputStream out;

	public OutputstreamRunnable(OutputStream output) {
		this.out = output;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		String str = "hello pipe";
		try {
			out.write(str.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

class InputstreamRunnable implements Runnable {

	private InputStream in;

	public InputstreamRunnable(InputStream in) {
		this.in = in;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		byte[] bs = new byte[1024];
		int len = -1;
		try {
			if ((len = in.read(bs)) != -1) {
				System.out.println(new String(bs, 0, len));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
相關文章
相關標籤/搜索