Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a shell script using ProcessBuilder

I am trying to run a script using Java and ProcessBuilder. When I try to run, I receive the following message: error=2, No such file or directory.

I dont know what I am doing wrong but here is my code (ps: I tried to execute just the script without arguments and the error is the same:

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};
ProcessBuilder p = new ProcessBuilder(command);

    try {  

        // create a process builder to send a command and a argument
        Process p2 = p.start(); 
        BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream()));
        String line;

        log.info("Output of running " + command + " is: ");
        System.out.println("Output of running " + command + " is: ");
        while ((line = br.readLine()) != null) {
            log.info(line);
        }

    }  
like image 446
Alvp Avatar asked Aug 08 '17 14:08

Alvp


People also ask

How does ProcessBuilder work in Java?

Constructs a process builder with the specified operating system program and arguments. This is a convenience constructor that sets the process builder's command to a string list containing the same strings as the command array, in the same order.

How do I run a terminal command in Java?

Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.

How do I change the working directory in ProcessBuilder?

ProcessBuilder. directory(File directory) method sets this process builder's working directory. Subprocesses subsequently started by this object's start() method will use this as their working directory.


1 Answers

Try replacing

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};

with

String[] command = {"/teste/teste_back/script.sh", argument1, argument};

Refer ProcessBuilder for more information.

ProcessBuilder(String... command)

Constructs a process builder with the specified operating system program and arguments.

like image 192
Beginner Avatar answered Nov 14 '22 22:11

Beginner