Java Processbuilder返回255

时间:2015-10-20 13:32:34

标签: java c++ command-line

我想运行带有文本输入和输出的C ++程序exe,但不知何故,processbuilder返回255并且不会将结果打印到输出txt。

    public static void runCommandPrompt(String[] cmds)  {
    ProcessBuilder compileProcessBuilder = new ProcessBuilder(cmds);
    Process compileProcess = null;
    try {
        compileProcess = compileProcessBuilder.start();
        int exitValue = compileProcess.waitFor();
        System.out.println(exitValue);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}



public static void main(String[] args){
    String[] evaluateCommands = { "cmd", 
               "/c",
               "cd C:\\TestPath & select.exe <C:\\input.txt >C:\\output.txt" };
    runCommandPrompt(evaluateCommands);
}

1 个答案:

答案 0 :(得分:3)

尝试将子进程的所有输出重定向到主进程。我相信你会看到错误的原因。

ProcessBuilder compileProcessBuilder = new ProcessBuilder(cmds);

// redirect all IO separately
compileProcessBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT);
compileProcessBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
compileProcessBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);

// or use a convenient call for all at once (thanks VGR to mention it)
compileProcessBuilder.inheritIO();

Process compileProcess = compileProcessBuilder.start();

<强>更新

如果您手动启动它,该过程会返回什么?也许他们真的会退回那些退出代码。

<强> run.cmd

select.exe <C:\input.txt >C:\output.txt
echo %ERRORLEVEL%