通过Java在unix中运行命令行

时间:2022-02-10 00:12:52

I have some problem. When I run the command:

我有一些问题。当我运行命令时:

openssl md5 "./build/outputs/apk/myApp.apk"

I get the result that I need, so openssl works fine. Then there is my code in Java:

我得到了我需要的结果,所以openssl工作正常。然后是我的Java代码:

String md5_cmd = "openssl md5 \"./build/outputs/apk/myApp.apk\"";

String md5Str = obj.executeCommand(md5_cmd);
String whichCmd = obj.executeCommand("which openssl"); //For testing executeCommand

 System.out.println(md5Str); //Not prints anything  
 System.out.println(whichCmd); //Prints the result just Fine    

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

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

}

So, the first command with "md5_cmd" not showing any output, although if I run it directly via command line its OK. The second command with "whichCmd" works as expected. Can you advise?

所以,第一个命令“md5_cmd”没有显示任何输出,虽然如果我直接通过命令行运行它就行了。带有“whichCmd”的第二个命令按预期工作。你能建议吗?

1 个解决方案

#1


1  

Instead of running command with a single string

而不是使用单个字符串运行命令

String md5_cmd = "openssl md5 \"./build/outputs/apk/myApp.apk\"";

Commands with arguments shall be run by using String[]

带参数的命令应使用String []运行

String[] md5_cmd = {"openssl", "md5", "./build/outputs/apk/myApp.apk"}; 

#1


1  

Instead of running command with a single string

而不是使用单个字符串运行命令

String md5_cmd = "openssl md5 \"./build/outputs/apk/myApp.apk\"";

Commands with arguments shall be run by using String[]

带参数的命令应使用String []运行

String[] md5_cmd = {"openssl", "md5", "./build/outputs/apk/myApp.apk"};