简体   繁体   English

在Java程序中执行命令行参数的问题

[英]Issue with executing command line arguments in a Java program

I have a problem with executing a command line - curl command, using a java program I have written to send data to an influxdb server. 我使用编写的Java程序将数据发送到influxdb服务器时执行命令行-curl命令时遇到问题。

This is the code for sending the command in my program: 这是在我的程序中发送命令的代码:

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());
}

The problem is that the data is not being send to the server, and the response from the command is zero. 问题是没有将数据发送到服务器,并且命令的响应为零。

The exact same command can be run from my command line, so there is nothing wrong with the syntax of the command. 可以从我的命令行运行完全相同的命令,因此该命令的语法没有任何问题。 I'm using a macintosh if that info is useful. 如果该信息有用,我正在使用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$ 

Is the code for executing command line arguments correct? 执行命令行参数的代码是否正确? Why is the command not being executed from my java program but working fine from the terminal? 为什么命令不是从我的Java程序执行,而是从终端正常工作?

Thank you. 谢谢。

Use String[] version of Runtime.exec . 使用Runtime.exec String[]版本。 So in place of 所以代替

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

Create command with arguments using String[] 使用String []创建带有参数的命令

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

And then call exec 然后打电话给exec

Runtime.getRuntime.exec(command);

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM