`
jianchen
  • 浏览: 336270 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

读写其他进程数据

阅读更多
package IO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class TestInOut implements Runnable {
	private Process p = null;

	public TestInOut() {
		try {
			p = Runtime.getRuntime().exec("java MyTest");
			new Thread(this).start();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

	}

	public void send() {
		try {
			OutputStream ops = p.getOutputStream();
			while (true) {
				ops.write("help\r\n".getBytes());
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

	}

	public void run() {
		try {
			InputStream in = p.getInputStream();
			BufferedReader bfr = new BufferedReader(new InputStreamReader(in));
			while (true) {
				String strLine = bfr.readLine();
				System.out.println(strLine);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	public static void main(String[] args) {
		TestInOut t = new TestInOut();
		t.send();
	}

}

class MyTest {
	public static void main(String[] args) throws IOException {
		while (true) {
			System.out.println("hi:"
					+ new BufferedReader(new InputStreamReader(System.in))
							.readLine());
		}
	}
}
 

在java程序中启动一个新的进程,该进程成为该程序的子进程。启动子进程可以使用Runtime.gerRuntime().exec
(string command)方法启动。参数是启动的具体命令,返回一个Process对象。通过这个process对象可以获得子进
程的输入输出流。从而实现父进程和子进程的通信。创建的子进程没有自己的终端或控制台。子进程的所有标准 io
(即 stdin,stdout,stderr)操作都将通过三个流重定向到父进程。父进程使用这些流来提供到子进程的输入和获得
从子进程的输出。调用Process的getOuputStream和getInputStream方法可以得到子进程以管道流的形式连接到
父进程的一个输出流和输入流对象。子进程从标准输入读取到的内容是父进程通过输出流对象写入管道的数据,子进程
写入标准输出的数据通过管道传送到了父进程的输入流对象中,父进程从这个输入流对象中读取到的内容就是子进程写
入到标准输出的数据。

 

我试验了以上代码,输出的结果都是null。有点想不通,张孝祥老师的就是这样做的,他却得到了结果。暂时记录下来,等有时间在回头看看,希望能找出原因。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics