如何在java程序中将参数传递给shell脚本 [英] How to pass parameter to shell script in java program

查看:1215
本文介绍了如何在java程序中将参数传递给shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

代码:

./test.sh argument1

java code:

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

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

How to pass argument for script in java code?

推荐答案

在最新版本的Java中创建进程的首选方法是使用 ProcessBuilder class这使得这很简单:

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

但如果你确实想/需要使用 Runtime.exec 无论出于何种原因,都有该方法的重载版本,允许明确指定参数:

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

这篇关于如何在java程序中将参数传递给shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆