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

编程入门 行业动态 更新时间:2024-10-23 23:29:44
本文介绍了如何在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脚本

本文发布于:2023-11-23 19:43:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622656.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   脚本   参数   程序   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!