简体   繁体   English

如何在Java程序中将参数传递给Shell脚本

[英]How to pass parameter to shell script in java program

i am trying to run this java code that calls the shell script on runtime. 我试图运行在运行时调用外壳程序脚本的Java代码。

when i run the script in terminal i am passing argument to script 当我在终端中运行脚本时,我正在将参数传递给脚本

code: 码:

./test.sh argument1

java code: Java代码:

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代码中传递脚本参数?

The preferred way to create processes in recent versions of Java is to use the ProcessBuilder class, which makes this very simple: 在Java的最新版本中创建进程的首选方法是使用ProcessBuilder类,这使得此过程非常简单:

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: 但是,如果出于某些原因确实想要/需要使用Runtime.exec ,则可以使用该方法的重载版本来明确指定参数:

Process proc = Runtime.getRuntime().exec(new String[]{"./test.sh", "kstc-proc"});

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();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM