【问题标题】:How to pass parameter to shell script in java program如何在java程序中将参数传递给shell脚本
【发布时间】:2013-06-03 09:45:40
【问题描述】:

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

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

代码:

./test.sh argument1

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 bash shell


【解决方案1】:

在最近的 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();

但是,如果您出于某种原因确实想要/需要使用Runtime.exec,则有overloaded versions of that method 允许显式指定参数:

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

【讨论】:

    【解决方案2】:

    这是一个非常简单的东西,你可以试试

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

    【讨论】:

      猜你喜欢
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2011-08-20
      • 2012-12-08
      相关资源
      最近更新 更多