如何从Java程序调用Shell脚本? [英] How can I call a shell script from a Java program?

查看:129
本文介绍了如何从Java程序调用Shell脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Eclipse中使用ubuntu 10.04.我创建了一个shell脚本,exam.sh:

I use ubuntu 10.04 with eclipse. I created a shell script, exam.sh:

#!/bin/bash 
echo "Hello World"

使用chmod 755考试.sh

with chmod 755 exam.sh

在命令行上,我可以执行./exam.sh // ok command showing me Hello World

On the command line, I can execute ./exam.sh // ok command showing me Hello World

我想用Java代码调用此exam.sh,这是我的Java代码:

I want to call this exam.sh with java code, this is my java code:

public static void main(String[] args) {    
Runtime r = Runtime.getRuntime();
Process p = null;
String cmd[] = {"/bin/bash","cd","/home/erdi/Desktop", ".","/","exam.sh"};

try {
    p = r.exec(cmd);
    System.out.println("testing...");//ok
} catch (Exception e) {
    e.printStackTrace();
}
}

这不起作用,我在哪里弄错了? 是的,我知道我可以通过Google进行搜索,但是找不到我的问题的答案.它提供了有关此功能的howTos和教程,但我没有找到答案.

This doesn't function, where did I make a mistake? Yes I know i can search by google but I didn't find an answer to my problem. It gives howTos and tutorials about this feature but I didn't find an answer.

推荐答案

尝试以下方法:

cmd[] = {"/bin/bash", "/home/ercan/Desktop/exam.sh"};

您可以直接在shell脚本上调用bash.要运行命令字符串(如cd),您需要使用-c开关.

You can just invoke bash on the shell script directly. To run a command string (like cd) you would need to use the -c switch.

如果您需要脚本的工作目录作为桌面,则可以使用Runtime.exec的另一个重载:

If you need the working directory of the script to be your Desktop, you can use another overload of Runtime.exec:

Process proc = runtime.exec(cmd, new String[0], new File("/home/ercan/Desktop"));

或者, ProcessBuilder 类使执行过程更好一些.

Alternatively, the ProcessBuilder class makes executing processes a bit nicer.

这篇关于如何从Java程序调用Shell脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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