2011-03-27 63 views
0

我想运行一个C/C++程序的使用exe文件java的.......并处理其输入和输出C可执行文件......处理用java

我的代码是

import java.io.*; 

class run2 { 
    public static void main(String[] args) throws java.io.IOException { 

    String[] command = new String[3]; 
    command[0] = "cmd"; 
    command[1] = "/C"; 
    // command[2] = "java Run1"; 
    command[2] = "start C:\\WE.EXE"; 

    Process p = Runtime.getRuntime().exec(command); 
    String i = "20"; 

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(
     p.getInputStream())); 
    BufferedWriter st = new BufferedWriter(new OutputStreamWriter(
     p.getOutputStream())); 

    String s = null; 
    System.out.println("Here is the standard output of the command:\n"); 
    s = stdInput.readLine(); 
    System.out.println(s); 
    st.write(i); 
    st.newLine(); 
    st.flush(); 
    while ((s = stdInput.readLine()) != null) { 
     System.out.println("Stdout: " + s); 
    } 

    try { 
     System.out.println("Exit status = " + p.waitFor()); 
    } 
    catch (InterruptedException e) { 
    } 
    stdInput.close(); 
    } 
} 

我得到它说管道已关闭 就帮我出个错误.....

+3

请包括跟踪和一切的完整错误 – 2011-03-27 02:54:51

回答

0

嗯,首先,如果没有在C:/一个WE.EXE,这可能是一个问题。如果没有进程启动,当然你不能对其输入/输出管道做任何事情。

但是,假设你有一个WE.EXE,你的错误可能是在:

st.flush(); 

你的应用程序在命令提示符下,或cmd.exe,开放WE.EXE,将采取谁了标准输入和标准的护理输出。您的电话stdInput.readLine();将等到WE.EXE,因此cmd.exe终止,此时输出流将被关闭(并且您显然无法写入到已关闭的管道中)。

所以,如果你想自己处理输入和输出,你应该直接启动WE.exe,如:

Process p = Runtime.getRuntime().exec("C://WE.EXE"); 

此外,您可以考虑使用ProcessBuilder,而不是Runtime.exec


小细节,但可以考虑使用Java's naming conventions ----例如,你的类名是RUN2(或更具描述性的),而不是RUN2。

0

您正在尝试从尚未存在的流(stdInput)读取数据。 直到WE.EXE程序写入内容才会存在。

只需等到您发送命令到程序。 换句话说,拿出第一个输入行,它会正常工作。

 
//s = stdInput.readLine(); 
System.out.println(s); 
st.write(i); 
st.newLine(); 
st.flush(); 
while ((s = stdInput.readLine()) != null) 
{ System.out.println("Stdout: " + s); }