【问题标题】:Write result from command line in file using Java使用Java将命令行结果写入文件
【发布时间】:2013-07-04 17:01:44
【问题描述】:

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

【问题讨论】:

    标签: java file command-line


    【解决方案1】:

    输出重定向是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
    

    (以上为Runtime's exec() method is not redirecting the output调整)

    【讨论】:

      【解决方案2】:

      尝试cmd.exe,如有必要,请提供路径。

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

      【讨论】:

        猜你喜欢
        • 2016-01-31
        • 1970-01-01
        • 1970-01-01
        • 2013-04-29
        • 1970-01-01
        • 1970-01-01
        • 2012-02-18
        • 2018-10-14
        • 1970-01-01
        相关资源
        最近更新 更多