Dim Dim - 5 months ago 26
Bash Question

Running command line in unix via Java

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:

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?

Answer

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[] md5_cmd = {"openssl", "md5", "./build/outputs/apk/myApp.apk"};