从 java 调用编译的 C++ exe 文件不起作用

Calling Compiled C++ exe file from java not working

我正在尝试从 java 调用 C++ 程序,我的 C++ 程序如下:

// A hello world program in C++
// hello.cpp

    #include<iostream>
    using namespace std;

    int main()
    {
        cout << "Hello World!";
        return 0;
    }

我所做的是我正在使用 minGW compiler 将 C++ 程序编译为 hello.exe,当我使用它时,它正在运行:

C:\Users\admin\Desktop>g++ -o hello hello.cpp

C:\Users\admin\Desktop>hello.exe
Hello World!

我创建了一个 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();
        }
    }
} 

检查 java 程序的输出:

C:\Users\admin\Desktop>javac Hello.java

C:\Users\admin\Desktop>java Hello

C:\Users\admin\Desktop>

为什么它不起作用,请帮助我?

成功了!!谢谢大家的支持!!

import java.io.File;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Hello {
    public static void main(String []args) {
        String filePath = "hello.exe";
        try {
                ProcessBuilder builder = new ProcessBuilder("hello.exe");
                Process process = builder.start();
                InputStream inputStream = process.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream), 1);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(line);
                }
                inputStream.close();
                bufferedReader.close();
            } catch (Exception ioe) {
                //ioe.printStackTrace();
            }
    }
} 

非常简单,您需要通过 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");
}

一般来说,您应该使用 ProcessBuilder 而不是 Process,它给您更多的选择