簡體   English   中英

無法通過exec Java方法運行linux命令

[英]Unable to run linux commands from exec Java method

我試圖從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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM