对C++部分的测试来自文章:
http://fair-jm.iteye.com/blog/1442267
C++代码
#include
#include
using namespace std;
void main(){
cout<<"hello world"<>i;
cout<
以上是试验目标的C++程序
以下是试验用的java程序:
Java代码
import java.io.*;
public class TestDemo
{
Process pc;
Runtime rt;
public TestDemo() throws Exception{
rt=Runtime.getRuntime();
String [] ss={"E:\\work\\Demo\\src\\Test.exe"};
pc=rt.exec(ss);
//readIt(); 注意这样也会产生堵塞
writeIt();
}
public static void main(String args[]) throws Exception{
new TestDemo();
}
public void writeIt(){
OutputStream fos=pc.getOutputStream();
PrintStream ps=new PrintStream(fos);
ps.print("another\n");
ps.flush(); //不加这个 后面的read就读不下去了
readIt();
}
public void readIt(){
InputStream ios=pc.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(ios));
String s;
try{
while((s=br.readLine())!=null){
System.out.println(s);
}
br.close();
ios.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
以上的做法 如果ReadIt()先写 则又会产生堵塞 所以最好用线程解决之。
堵塞的产生:你先读取输入流(相当于被调用程序的输出流getInputStream)的话 如果遇到输入的地方(cin)则输入流堵塞,
等待输入(如果不用线程的话就一直堵在那,根本无法通过输出流(相当于被调用程序的输入流)无法输入信息到进程里面去)。
如果你先用输出流输入到被调用程序里面去,但遗忘了用flush(),则数据根本就无法传输。
以下是线程的解决方法:
Java代码
package aa;
import java.io.*;
public class TestDemo
{
Process pc;
Runtime rt;
public TestDemo() throws Exception{
rt=Runtime.getRuntime();
String [] ss={"E:\\work\\Demo\\src\\Test.exe"};
pc=rt.exec(ss);
new Thread(new Input()).start();
Thread.sleep(500);
new Thread(new Output()).start();
}
public static void main(String args[]) throws Exception{
new TestDemo();
}
class Output implements Runnable
{
public void run(){
OutputStream fos=pc.getOutputStream();
PrintStream ps=new PrintStream(fos);
ps.print("another\n");
System.out.println("已经输出");
ps.flush();
}
}
class Input implements Runnable
{
public void run(){
InputStream ios=pc.getInputStream();
BufferedReader brd=new BufferedReader(new InputStreamReader(ios));
String s;
try{
while((s=brd.readLine())!=null){
System.out.println(s);
}
}catch(Exception e){
}
pc.destroy();
}
}
}
以下是对python的测试:java代码:
public static void main(String args[]) {
rt = Runtime.getRuntime();
String ss = "python C:\\Users\\ciabok\\Desktop\\test.py";
try {
pc = rt.exec(ss);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// readIt(); 注意这样也会产生堵塞
writeIt();
}
python代码:
# -*- coding=utf-8 -*-
if __name__=='__main__':
print 'test'
a=raw_input()
print a
经过测试,如果写成 a=input() 会无法读取,
原因不明,暂时没找到相关资料。