San*_*ool 2 c++ java exe mingw
我试图从java和我的C++程序中调用C++程序,如下所示:
// A hello world program in C++
// hello.cpp
#include<iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我所做的是minGW compiler 用于将C++程序编译为hello.exe,当我使用它时,它正在工作:
C:\Users\admin\Desktop>g++ -o hello hello.cpp
C:\Users\admin\Desktop>hello.exe
Hello World!
Run Code Online (Sandbox Code Playgroud)
我已经创建了一个java程序,它应该调用C++编译的程序(hello.exe),但我的java程序是注意调用exe,我的程序如下:
//Hello.java
public class Hello {
public static void main(String []args) {
String filePath = "hello.exe";
try {
Process p = Runtime.getRuntime().exec(filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
检查java程序的输出:
C:\Users\admin\Desktop>javac Hello.java
C:\Users\admin\Desktop>java Hello
C:\Users\admin\Desktop>
Run Code Online (Sandbox Code Playgroud)
为什么不工作,请帮帮我?
很简单,你需要通过Processs 读取过程的输出InputStream,例如......
String filePath = "hello.exe";
if (new File(filePath).exists()) {
try {
ProcessBuilder pb = new ProcessBuilder(filePath);
pb.redirectError();
Process p = pb.start();
InputStream is = p.getInputStream();
int value = -1;
while ((value = is.read()) != -1) {
System.out.print((char) value);
}
int exitCode = p.waitFor();
System.out.println(filePath + " exited with " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.err.println(filePath + " does not exist");
}
Run Code Online (Sandbox Code Playgroud)
一般来说,你应该使用ProcessBuilder过Process,它为您提供了更多的选择
| 归档时间: |
|
| 查看次数: |
1274 次 |
| 最近记录: |