使用Java从文件中的命令行写入结果

时间:2013-07-07 01:03:23

标签: java file command-line

我尝试从Java代码运行命令行。

public void executeVcluto() throws IOException, InterruptedException {
    String command = "cmd /c C:\\Users\\User\\Downloads\\program.exe C:\\Users\\User\\Downloads\\file.txt 5 >> C:\\Users\\User\\Downloads\\result.txt";
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();
    if (process.exitValue() == 0) {
        System.out.println("Command exit successfully");
    } else {
        System.out.println("Command failed");
    }

}

但是,不会创建应该写入输出结果的文件result.txt。当我从Windows上的cmd执行此命令时,将创建文件并将结果写入其中。我得到Command exit成功消息。有人能帮助我吗?

2 个答案:

答案 0 :(得分:3)

输出重定向是shell特性,java Process不明白。

其他一些替代方案 1.使用上面的行创建一个批处理文件,并使用ProcessBuilder / Runtime调用它 2.使用ProcessBuilder并使用输出流重定向输出。  示例(它适用于shell,也适用于批处理文件)在这里

ProcessBuilder builder = new     ProcessBuilder("cmd", "/c", "C:\\Users\\User\\Downloads\\program.exe", "C:\\Users\\User\\Downloads\\file.txt" , "5");
builder.redirectOutput(new File("C:\\Users\\User\\Downloads\\result.txt"));
builder.redirectError(new File("C:\\Users\\User\\Downloads\\resulterr.txt"));

Process p = builder.start(); // throws IOException

(上面是从Runtime's exec() method is not redirecting the output调整的)

答案 1 :(得分:0)

如有必要,请尝试cmd.exe,包括路径。

您正在创建一个全新的流程,这与向shell发出命令不同。

相关问题