32

How am I to execute a command in Java with parameters?

I've tried

Process p = Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php -m 2"});

which doesn't work.

String[] options = new String[]{"option1", "option2"};
Runtime.getRuntime().exec("command", options);

This doesn't work as well, because the m parameter is not specified.

sam1370
3532 silver badges18 bronze badges
asked Aug 20, 2011 at 20:27

4 Answers 4

30

See if this works (sorry can't test it right now)

Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php", "-m", "2"});
answered Aug 20, 2011 at 20:40
Sign up to request clarification or add additional context in comments.

1 Comment

This should mention that this is important to set one String per command; parameter or value. So "-m 2" might not work. This need to be "-m", "2"
26

Use ProcessBuilder instead of Runtime#exec().

ProcessBuilder pb = new ProcessBuilder("php", "/var/www/script.php", "-m 2");
Process p = pb.start();
answered Aug 20, 2011 at 20:35

1 Comment

If that doesn't work: new ProcessBuilder("php", "/var/www/script.php", "-m", "2");
1

The following should work fine.

Process p = Runtime.getRuntime().exec("php /var/www/script.php -m 2");
answered Aug 20, 2011 at 20:34

Comments

0

Below is java code for executing python script with java.

ProcessBuilder:

  • First argument is path to virtual environment
  • Second argument is path to python file
  • Third argument is any argumrnt you want to pass to python script
public class JavaCode {
 public static void main(String[] args) throws IOException {
 String lines = null;
 ProcessBuilder builder = new ProcessBuilder("/home/env-scrapping/bin/python",
 "/home/Scrapping/script.py", "arg1");
 Process process = builder.start();
 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
 while ((lines = reader.readLine())!=null) {
 System.out.println("Line: " + lines);
 }
 }
}

First is virtual environment path

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.