从Java代码运行Shell脚本并传递参数 [英] Running shell script from java code and pass arguments

查看:118
本文介绍了从Java代码运行Shell脚本并传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Java程序执行shell脚本.我已经使用Runtime类实现了它.下面是我实现的代码

I am executing a shell script from Java program. I have implemented it using Runtime class. Below is the code I implemented

final StringBuilder sb = new StringBuilder("test.sh");
sb.append("/path to/my/text file");

final Process p = Runtime.getRuntime().exec(sb.toString());

这里sb是字符串缓冲区对象,我在其中附加参数并在exec方法中使用它.但是问题是我传递的参数"/path to/my/text file"被认为是4个参数

Here sb is string buffer object where I append my parameters and use it in exec method. But the problem is the parameter I pass "/path to/my/text file" is considered as 4 parameters

/path
 to
/my/text
 file

但是,如果在shell中作为test.sh"//my/text文件的路径"运行,则将其作为单个参数.如何使用Java代码实现相同的功能,在Java代码中,我需要将此路径以空格作为单个参数.任何请问都会很感激.

But if run in shell as test.sh "/path to/my/text file" which is taken as single parameter. How can I achieve the same using Java code, where I need to consider this path with spaces as single argument. Any please will be really appreciable.

推荐答案

使用 ProcessBuilder 是它的目的,旨在使您的生活更轻松

Use ProcessBuilder , it's what it's designed for, to make your life easier

ProcessBuilder pb = new ProcessBuilder("test.sh", "/path", "/my/text file");
Process p = pb.start();

这篇关于从Java代码运行Shell脚本并传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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