从java调用Compiled C ++ exe文件无法正常工作

时间:2015-02-06 05:51:00

标签: java c++ mingw exe

我试图从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>

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

2 个答案:

答案 0 :(得分:5)

很简单,您需要通过Process s 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,它会为您提供更多选项

答案 1 :(得分:0)

工作!!谢谢你们的支持!!

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();
            }
    }
}