Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java程序中如何将参数传递给shell脚本_Java_Bash_Shell - Fatal编程技术网

java程序中如何将参数传递给shell脚本

java程序中如何将参数传递给shell脚本,java,bash,shell,Java,Bash,Shell,我正在尝试运行在运行时调用shell脚本的java代码 在终端中运行脚本时,我将参数传递给脚本 代码: java代码: public class scriptrun { public static void main(String[] args) { try { Process proc = Runtime.getRuntime().exec("./te

我正在尝试运行在运行时调用shell脚本的java代码

在终端中运行脚本时,我将参数传递给脚本

代码:

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

如何在java代码中为脚本传递参数?

在最新版本的java中创建进程的首选方法是使用类,这使得这一点非常简单:

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();
但是,如果出于任何原因您确实想/需要使用
Runtime.exec
,则有一些方法允许显式指定参数:

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

在最新版本的Java中,创建进程的首选方法是使用类,这使得创建过程非常简单:

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();
但是,如果出于任何原因您确实想/需要使用
Runtime.exec
,则有一些方法允许显式指定参数:

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

这里有一些非常简单的东西,你可以试试

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

这里有一些非常简单的东西,你可以试试

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();
        }
    }
}
替换使用。可能的重复使用。可能的重复使用