您的位置:首页 > 编程语言 > Java开发

IO 输入与输出(9)-- Java程序与其他进程的数据通信

2011-04-18 22:05 756 查看
在Java程序中,可以启动其他的应用程序,这种在Java中启动的进程称为子进程,启动子进程的Java程序就称为父进程。
 
在Java程序中,可以使用Process类实例对象来表示子进程,子进程的标准输入和输出不再连接到键盘和显示器,而是以管道流的形式连接到父进程的一个输出流和输入流对象上。
 
调用Process类的getOutputStream和getInputStream方法可以获得连接到子进程的输出流和输入流对象。
 
下面直接看一个例子吧:
从TestInOut.java中启动java.exe命令执行另外一个MyTest.java,TestInOut.java和MyTest.java通过进程间的管道相互传递数据。
 

 MyTest.java
 
import java.io.*;

public class MyTest {

public static void main(String[] args) throws IOException {
while (true) {
String str = new BufferedReader(new InputStreamReader(System.in))
.readLine();// 读取父进程的数据
if (str != null) {
System.out.println("re:" + str); //添加回复
} else {
return;
}
}
}

}


 

TestInOut.java
 
import java.io.*;

public class TestInOut implements Runnable {

Process process = null;

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

// 向子进程发送数据
public void send() {
OutputStream os = process.getOutputStream();
while (true) {
try {
os.write("hello/r/n".getBytes()); // 不停的写入hello
} catch (IOException e) {
e.printStackTrace();
}
}
}

// 从子进程读取数据
public void run() {
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String strLine;
try {
while (true) {
strLine = br.readLine();// 读取一行信息
if(strLine != null){
System.out.println(strLine);
}else{
return;
}
}
} catch (IOException e) {
e.printStackTrace();
}

}

public TestInOut() {
try {
this.process = Runtime.getRuntime().exec("java MyTest");// 调用java.exe执行"java MyTest"命令
} catch (IOException e) {
e.printStackTrace();
}
new Thread(this).start(); // 启动一个新的线程
}

}


 需要注意的是:在管道缓冲区满了以后,与PipedInputStream相连的PiredOutputStream无法再写入新的数据,PipedOutputStream.write()方法将处于阻塞状态。

 版权声明: 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java io string class null thread