Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash commands using java process builder for copying file

Iam using the following java code for executing bash commands,when trying to copy files the function is returning non zero value but iam able to create files.

copy command : cp demo.txt /shared

output is: 127

create file command : echo 'sample text' > demo.txt

output is: 0

public static int run(final String command)  
{
    String[] finalCommand;
    Process process=null;
    int temp=0;

        finalCommand = new String[3];
        finalCommand[0] = "bash";//"/usr/bin/ksh";
        finalCommand[1] = "-c";
        finalCommand[2] = command;

try {
    final ProcessBuilder processBuilder = new ProcessBuilder(finalCommand);
    processBuilder.redirectErrorStream(true);
    process = processBuilder.start();
    temp=process.waitFor();
    } 
    catch (IOException e) 
    { 
    System.out.println( e.getMessage()); 
    } 
    catch (InterruptedException e) { 
    System.out.println(e.getMessage()); 
    }
    return temp;
}

please help

like image 733
Garikapati Praveenkumar Avatar asked May 20 '26 06:05

Garikapati Praveenkumar


1 Answers

One possibility for cp failing and echo working is due to cp being an external command and echo a built-in command.

An external command can only be found by its file name if the PATH environment variable is set and exported.

But in a situation like this, don't ever rely on PATH - use the full pathname:

String command = "/bin/cp demo.txt /shared";

Also: Do you have write permission in /shared?

like image 103
laune Avatar answered May 22 '26 20:05

laune