Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3350600
  • 博文数量: 1450
  • 博客积分: 11163
  • 博客等级: 上将
  • 技术积分: 11101
  • 用 户 组: 普通用户
  • 注册时间: 2005-07-25 14:40
文章分类

全部博文(1450)

文章存档

2017年(5)

2014年(2)

2013年(3)

2012年(35)

2011年(39)

2010年(88)

2009年(395)

2008年(382)

2007年(241)

2006年(246)

2005年(14)

分类: LINUX

2007-03-02 17:00:19

    

A : java 调用shell脚本的问题。我该怎么写

Process proc = Runtime.getRuntime().exec("/bin/sh run.sh stop");
其中run.sh 是我写的一个启动和停止一个java的程序。
这样写对吗?我运行的时候一直有错


Q:奇怪,为什么你要exec("/bin/sh run.sh stop")?

不能直接exec("run.sh stop")吗?
在你的run.sh的第一行加入
#!/bin/sh

然后在shell下运行chmod a+x run.sh就可以把你的run.sh变成可执行文件了。

另外,要提醒的是你的java程序运行的目录和你shell用户可能不同,所以建议用全路径,比如
exec("/root/bin/run.sh stop")



如果你有多个参数,或者参数中有空格或特殊字符的,可以用如下方法:
try {
// Execute a command without arguments
String command = "ls";
Process child = Runtime.getRuntime().exec(command);

// Execute a command with an argument
command = "ls /tmp";
child = Runtime.getRuntime().exec(command);
} catch (IOException e) {
}
If an argument contain spaces, it is necessary to use the overload that requires the command and its arguments to be supplied in an array:
    try {
// Execute a command with an argument that contains a space
String[] commands = new String[]{"grep", "hello world", "/tmp/f.txt"};
commands = new String[]{"grep", "hello world", "c:\\Documents and Settings\\f.txt"};
Process child = Runtime.getRuntime().exec(commands);
} catch (IOException e) {
}
阅读(1312) | 评论(0) | 转发(0) |
0

上一篇:建立 job

下一篇:java 调用 shell 得到返回值

给主人留下些什么吧!~~