gpt4 book ai didi

java - 无法从 exec Java 方法运行 linux 命令

转载 作者:太空宇宙 更新时间:2023-11-04 03:46:27 25 4
gpt4 key购买 nike

我正在尝试从 Java exec 方法执行 cf 命令,而不是从 Linux 终端手动输入。我从终端传递了我所做的确切语法但是,在将第一个参数传递给方法时我收到错误,因为它包含空格我不确定如何调试它?

直接从 Linux 终端

root@devopsops:/home/Data/free# cf create-service 'IBM Analytics for Hadoop' Free 'IBM_Analytics_for_Hadoop'_APP
Creating service IBM_Analytics_for_Hadoop_APP in org All_Testing / space monitor-ms1 as xyz@gmail.com...
OK

...

如果我从 java 中的 exec 方法运行相同的命令,我会收到以下错误

cf create-service 'IBM Analytics for Hadoop' Free 'IBM_Analytics_for_Hadoop'_APP
Here is the standard output of the command:

FAILED
Incorrect Usage.

NAME:
create-service - Create a service instance

ALIAS:
cs

USAGE:
cf create-service SERVICE PLAN SERVICE_INSTANCE

Java代码

主要方法

obj.cfCreateService("'IBM Analytics for Hadoop'","Free");

cfCreateService方法

public String cfCreateService(String servicename, String planname){

String s = null;
StringBuffer log = new StringBuffer("");

try {
String appname= servicename.replaceAll(" ", "_")+"_APP";
String command="cf create-service "+servicename+" "+ planname +" "+ appname;
System.out.println(command);
Process p = Runtime.getRuntime().exec(command);

BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));

BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));

// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
log.append(s+"\n");

}


}


}

最佳答案

您正在做的事情看起来是正确的,但也许您可以尝试将参数封装到 exec() 的数组参数中:

 Process p = Runtime.getRuntime().exec(new String[]{"cf", "create-service", servicename, planname, appname});

而不是

        String command="cf create-service "+servicename+" "+ planname +" "+ appname; 
Process p = Runtime.getRuntime().exec(command);

关于java - 无法从 exec Java 方法运行 linux 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28037441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com