在java中打印c++ .exe文件的输出

Print output of c++ .exe file in java

本文关键字:文件 输出 exe c++ java 打印      更新时间:2023-10-16

我想从java运行c++ .exe文件,也想打印.exe文件的输出。我尝试并成功地从java运行c++ .exe文件,但我不知道如何使用java打印c++ .exe文件的输出(在java输出字段中),我尝试使用processExitValue和等待方法,但没有得到所需的输出。java代码在这里

int processExitVal = 0;
         try {
        Process p = Runtime.getRuntime().exec("cmd /c  start rs.exe");
        processExitVal = p.waitFor();
       // p.getOutputStream();
        //InputStreamReader ir=new InputStreamReader(p.getInputStream());
       //BufferedReader t = new BufferedReader((new InputStreamReader(p.getInputStream())));
       // int y=Integer.parseInt(t.readLine());
        InputStream in=p.getInputStream();
        System.out.println(in.read());
        //System.out.println("output"+Process.getOutputStream());
        } catch (IOException e) {
        System.out.println("IOException");
        e.printStackTrace();
        } catch (InterruptedException e) {
        System.out.println("InterruptedException");
        e.printStackTrace();
       }
       System.out.println(processExitVal);
       System.out.println("Execution complete");
}
如果你能帮我解决这个问题,我会很感激的。提前感谢

您可以使用Scanner,然后从中读取行。您确定您的进程在标准输出上写入了一些内容吗?

编辑:

read():从输入流中读取下一个字节的数据。

你必须使用扫描器:

Scanner scan = new Scanner(p.getInputStream());
String line = scan.getNextLine();

关于Deestan的回答:getInputStream()在这里是正确的方法,我们想要过程的输出,这是应用程序的输入。

使用"rs.exe"代替"cmd/c start rs.exe"

例如:

Process process = Runtime.getRuntime().exec("rs.exe");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while((line = in.readLine()) != null) {
  System.out.println(line);
}