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

使用Java将命令行中的结果写入文件,java,file,command-line,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"; P

我试图从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执行此命令时,将创建文件并将结果写入其中。我成功获得命令退出消息。有人能帮我吗?

试试
cmd.exe
,如果需要,包括路径


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

输出重定向是shell的功能,java进程不理解这一点

其他一些选择是 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