31

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.

5 Answers 5

29

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

Runtime.getRuntime().exec(new String[]{"php","/var/www/script.php", "-m", "2"});
1
  • 1
    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"
    – AxelH
    Aug 24, 2018 at 12:53
26

Use ProcessBuilder instead of Runtime#exec().

ProcessBuilder pb = new ProcessBuilder("php", "/var/www/script.php", "-m 2");
Process p = pb.start();
1
  • 2
    If that doesn't work: new ProcessBuilder("php", "/var/www/script.php", "-m", "2");
    – Matt Ball
    Aug 20, 2011 at 20:52
1

The following should work fine.

Process p = Runtime.getRuntime().exec("php /var/www/script.php -m 2");
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
  • 1
    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.
    – Community Bot
    Sep 5, 2022 at 16:30
0

You can try my jaxec library:

import com.yegor256.Jaxec;
new Jaxec("php", "/var/www/script.php -m 2").exec();

It will not only execute this shell command, but also:

  • Log the entire output
  • Redirect stderr to stdout
  • Check the exit code and throw exception if it's not zero
  • Wait until the command stops

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.