How to pass parameter to shell script in java prog

2019-03-03 08:17发布

i am trying to run this java code that calls the shell script on runtime.

when i run the script in terminal i am passing argument to script

code:

./test.sh argument1

java code:

public class scriptrun
    {
        public static void main(String[] args)
            {
            try
                {
                    Process proc = Runtime.getRuntime().exec("./test.sh");
                    System.out.println("Print Test Line.");
                }
                catch (Exception e)
                {
                    System.out.println(e.getMessage());
                    e.printStackTrace();
                }
            }
    } 

How to pass argument for script in java code?

标签: java bash shell
2条回答
甜甜的少女心
2楼-- · 2019-03-03 08:59

Here is something very simple you can try

public class JavaRunCommandExample {

    public static void main(String[] args) {

        Runtime r = Runtime.getRuntime();
        Process p = null;
        String cmd[] = {"./test.sh","argument1"};

        try {
            p = r.exec(cmd);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
查看更多
干净又极端
3楼-- · 2019-03-03 09:14

The preferred way to create processes in recent versions of Java is to use the ProcessBuilder class, which makes this very simple:

ProcessBuilder pb = new ProcessBuilder("./test.sh", "kstc-proc");
// set the working directory here for clarity, as you've used a relative path
pb.directory("foo");
Process proc = pb.start();

But if you do want to/need to use Runtime.exec for whatever reason, there are overloaded versions of that method that allow the arguments to be specified explicitly:

Process proc = Runtime.getRuntime().exec(new String[]{"./test.sh", "kstc-proc"});
查看更多
登录 后发表回答