Confusing command line execution in Java

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Confusing command line execution in Java



Recently, I had some trouble with command line execution in a Java application. Everything goes smooth when I execute a command like this:


try
Process a = Runtime.getRuntime().exec("cmd /c mkdir C:\Users\CA_LTD\TryoutDir");
catch (IOException e1)
// TODO Auto-generated catch block
e1.printStackTrace();



Then a specific directory is created. However, when I want to do some more complicated it does not go very well. For example, when I want to execute a command which creates an APK file for my application project:


try
Process a = Runtime.getRuntime().exec("cmd /c C:\Users\CA_LTD\AndroidStudioProjects\AMBITION gradlew assembleRelease");
catch (IOException e1)
// TODO Auto-generated catch block
e1.printStackTrace();



Why is that happening? Normal one-phrase command go in and the other don't?





What issue are you facing? What error is coming ?
– Ashishkumar Singh
Aug 2 at 11:31





might it be because you have spaces in your folder name, and the exec assumes the last two words are seperate params?
– Stultuske
Aug 2 at 11:40





Consider using ProcessBuilder instead of a single string for the command so you can really setup which value is passed to each parameter.
– Cristian Ramon-Cortes
Aug 2 at 11:48




2 Answers
2



The String passed to the exec method is automatically parsed to define the parameters of the command. Since your path contain spaces (and might contain special characters too), you should consider using ProcessBuilder to construct your command.


exec



Moreover, the constructor of the ProcessBuilder is the command to execute but you can also change the working directory using the directory method.


try
String cmd = "cmd",
"/c",
"gradlew",
"assembleRelease";
ProcessBuilder pb = new ProcessBuilder(cmd);
// Change working directory
pb.directory(new File("C:\Users\CA_LTD\AndroidStudioProjects\AMBITION"));
// Run command
Process p = pb.start();
// Wait for completion
int exitValue = p.waitFor();
// Check exit value
if (exitValue != 0)
// TODO: Define your behaviour when process exits with non-zero exit value

// Print command output
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream());
String outLine = null;
while ( (outLine = reader.readLine()) != null)
System.out.println(outLine);


// Print command error
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream());
String errLine = null;
while ( (errLine = reader.readLine()) != null)
System.err.println(errLine);


// Throw exit value exception
throw new Exception("ERROR: CMD process exited with non-zero value: " + exitValue);

catch (IOException ioe)
ioe.printStackTrace();



If you don't want to check the exit value of the command (in Windows the exit value is a pseudo environment variable named errorlevel as described in here ), you can just do:


errorlevel


try
String cmd = "cmd",
"/c",
"gradlew",
"assembleRelease";
ProcessBuilder pb = new ProcessBuilder(cmd);
// Change working directory
pb.directory(new File("C:\Users\CA_LTD\AndroidStudioProjects\AMBITION"));
// Run command
Process p = pb.start();
// Wait for completion
p.waitFor();
catch (IOException ioe)
ioe.printStackTrace();





I don't really know what are you expecting to execute with the cmd command so you should consider using a different cmd definition.
– Cristian Ramon-Cortes
Aug 2 at 12:00






I want to make an APK file from that project by using that command. What is that non-zero exit value and why should I define my behaviour? Is the code: int exitValue = p.waitFor(); // Check exit value if (exitValue != 0) // TODO: Define your behaviour when process exits with non-zero exit value throw new Exception("ERROR: CMD process exited with non-zero value: " + exitValue); really needed?
– Jonathan Crane
Aug 2 at 14:27





I do not know what should I do if I have non-zero exit value. Your code does not work. Maybe it is because of that I have that exception with non-zero exit value.
– Jonathan Crane
Aug 2 at 14:39





???? Can I get an answer?
– Jonathan Crane
Aug 3 at 9:18





If you were working only with the console, which will be the command you will execute? The exit value is the return code of the command (which can be checked with the pseudo environment variable named errorlevel). I will add a version without checking the exit value
– Cristian Ramon-Cortes
Aug 6 at 12:19



So after a solution posted by @CristianRamon-Cortes I got this output:


FAILURE: Build failed with an exception.
Starting a Gradle Daemon, 1 incompatible and 1 stopped Daemons could not be reused, use --status for details
NDK is missing a "platforms" directory.
If you are using NDK, verify the ndk.dir is set to a valid NDK directory. It is currently set to C:UsersCA_LTDAppDataLocalAndroidSdkndk-bundle.
If you are not using NDK, unset the NDK variable from ANDROID_NDK_HOME or local.properties to remove this warning.

Incremental java compilation is an incubating feature.

BUILD FAILED

Total time: 29.414 secs

* What went wrong:
Task 'assebleRelease' not found in root project 'AMBITION'. Some candidates are: 'assembleRelease'.

* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Exception in thread "main" java.lang.Exception: ERROR: CMD process exited with non-zero value: 1
at com.example.test.TestingCmd.main(TestingCmd.java:43)



EDIT: And heck, it was only about a letter "m" in the word assemble...
Thank You @CristianRamon-Cortes!!!






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard