Executing shell-script with parameters from java

前端 未结 3 858
一生所求
一生所求 2021-02-14 07:48

I have been googling for some time, and everyone seems to have a different solution, none of which appear to be working for me.

I have tried both ProcessBuilder

3条回答
  •  别那么骄傲
    2021-02-14 08:22

    As already mentioned, tilde is a shell-specific expansion which should be handled manually by replacing it with the home directory of the current user (e.g with $HOME if defined).

    Besides the solutions already given, you might also consider using commons-io and commons-exec from the Apache Commons project:

    ...
    import org.apache.commons.exec.CommandLine;
    import org.apache.commons.exec.DefaultExecutor;
    import org.apache.commons.exec.Executor;
    import org.apache.commons.io.FileUtils;
    ...
    CommandLine cmd = new CommandLine("path/to/shellscript.sh");
    cmd.addArgument("foo");
    cmd.addArgument("bar");
    
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(FileUtils.getUserDirectory());
    exec.execute(cmd);
    ...
    

提交回复
热议问题