【问题标题】:Issue with executing command line arguments in a Java program在 Java 程序中执行命令行参数的问题
【发布时间】:2016-06-19 17:11:35
【问题描述】:

我在执行命令行时遇到问题 - curl 命令,使用我编写的 java 程序将数据发送到 influxdb 服务器。

这是在我的程序中发送命令的代码:

public static void main (String[] args){
    String command = "curl -i -XPOST 'http://localhost:8086/write?db=speed' --data-binary 'test,dataset=perf cpu=10'";  
    execcommand (command);
}

public static void execcommand (String command){
    StringBuffer output = new StringBuffer();
    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader =
            new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(output.toString().length());
}

问题是数据没有发送到服务器,命令的响应为零。

可以从我的命令行运行完全相同的命令,因此该命令的语法没有任何问题。如果该信息有用,我正在使用 macintosh。

My-MBP:~ MB$ curl -i -XPOST 'http://localhost:8086/write?db=speed' --data-binary 'test,dataset=perf cpu=10'
HTTP/1.1 204 No Content
Request-Id: 3f866002-3640-11e6-8988-000000000000
X-Influxdb-Version: 0.13.0
Date: Sun, 19 Jun 2016 17:07:05 GMT

My-MBP:~ MB$ 

执行命令行参数的代码是否正确?为什么命令没有从我的 java 程序中执行,但在终端上运行正常?

谢谢。

【问题讨论】:

    标签: java shell curl


    【解决方案1】:

    使用String[] 版本的Runtime.exec。所以代替

    String command = "curl -i -XPOST 'http://localhost:8086/write?db=speed' --data-binary 'test,dataset=perf cpu=10'";
    

    使用 String[] 创建带参数的命令

    String[] command = {"curl", "-i", "-XPOST", "http://localhost:8086/write?db=speed", "--data-binary", "test,dataset=perf cpu=10"};
    

    然后调用exec

    Runtime.getRuntime.exec(command);
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 2011-01-16
      • 2015-06-15
      • 2017-05-03
      • 1970-01-01
      相关资源
      最近更新 更多