kgopi
kgopi

Reputation: 151

Unable to execute a command if it contains spaces using java

Issue:- If the executable command contain's any spaces then System.exec is omitting the string content after the first space.

For example:- if command="/opt/GUIInstaller/installers/abc def gh.bin" Then java is executing command up-to /opt/GUIInstaller/installers/abc only and resulting a error like java.io.IOException: "/opt/GUIInstaller/installers/abc": error=2, No such file or directory

protected void launch(final String command) 
{
    try 
    {
        if(command.contains("null"))
        {
            logger.error("Installer is not located in the specified folder: "+command);
            System.exit(0);
        }
        runTime.exec(command);
    }
    catch (IOException ioException) {
        logger.error(ioException.getMessage(), ioException);
    }
}

Is I am doing any mistake, please help me to solve this issue.

Environment:- Java7 update9 + RHEL6

Upvotes: 0

Views: 1226

Answers (2)

Dropout
Dropout

Reputation: 13876

Add

if(command.contains(" ")){command.replace(" ","\\ ");}

before the runTime.exec(command);

This basically just replaces spaces with escaped spaces..

Edit: Or to make it smoother try to execute this

runTime.exec(command.replace(" ","\\ "));

without adding the aforementioned line..

Upvotes: 0

creinig
creinig

Reputation: 1580

As described in the javadocs of Process#exec(), exec(String) simply splits the given command string into tokens via StringTokenizer. If you do that job jourself by passing tokens to exec(), spaces in there are no problem:

runTime.exec(new String[] {"/opt/GUIInstaller/installers/abc def gh.bin", "--param1=foo"});

Upvotes: 3

Related Questions