关于使用Java程序与其它进程的数据通信时管道已结束的问题
这个程序包含两个类:TestInOut.java与MyTest.java。
TestInOut.java作为父进程,MyTest.java作为子进程。
在TestInOut.java中使用Process类调用Runtime.getRuntime().exec("java MyTest")函数来启动子进程并获得一个Process对象。不知为什么,运行时老是报错,说是管道已结束,弄了好久,现在还没搞清楚。请高手们帮我看看是什么原因,怎么改,谢谢!
两个类的代码如下:
TestInOut.java:
import java.io.*;
public class TestInOut implements Runnable{
Process p = null;
public TestInOut() {
try {
p = Runtime.getRuntime().exec("java MyTest");
} catch (IOException e) {
e.printStackTrace();
}
new Thread(this).start();
}
public static void main(String[] args) {
TestInOut tio = new TestInOut();
tio.send();
}
public void send() {
try{
OutputStream os = p.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
while (true) {
bw.write("help\r\n".toCharArray());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader (new InputStreamReader(is));
String str = null;
try{
while(true) {
str = br.readLine();
if(str != null) {
System.out.println(str);
} else {
return;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
MyTest.java:
import java.io.*;
public class MyTest {
public static void main(String[] args) throws IOException {
BufferedReader bfr= new BufferedReader(new InputStreamReader(System.in));
String str = null;
while(true) {
str = bfr.readLine();
if(str != null) {
System.out.println("hi:" + str);
} else {
return;
}
}
}
}
运行结果:
java.io.IOException: 管道已结束。
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:260)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105)
at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:336)
at sun.nio.cs.StreamEncoder$CharsetSE.implWrite(StreamEncoder.java:395)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:136)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:191)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:111)
at java.io.BufferedWriter.write(BufferedWriter.java:181)
at java.io.Writer.write(Writer.java:104)
at com.srong.inout.TestInOut.send(TestInOut.java:26)
at com.srong.inout.TestInOut.main(TestInOut.java:18)
|
|