`
hanqunfeng
  • 浏览: 1527654 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java调用Shell脚本

    博客分类:
  • JAVA
阅读更多

原文地址:http://hi.baidu.com/qiu1157/blog/item/6b4f02362a7c0c360b55a9e3.html

在你的test.sh的第一行加入
#!/bin/sh

然后在shell下运行chmod a+x test.sh就可以把你的test.sh变成可执行文件了。
另外,要提醒的是你的java程序运行的目录和你shell用户可能不同,所以建议用全路径,比如
Runtime.getRuntime().exec ("/root/bin/test.sh");

----------------------------------------------------------------------------------------------

如果需要输出信息的话

Process process = Runtime.getRuntime().exec("/root/bin/test.sh");
InputStreamReader ir = new InputStreamReader(process.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null)
System.out.println(line);
input.close();
ir.close();

-----------------------------------------------------------------------------------------------

注意UNIX系统的权限问题 =..=

-----------------------------------------------------------------------------------------------

完整代码:

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class RunShell {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//Runtime.getRuntime().exec("/root/bin/test.sh");
Process process = Runtime.getRuntime().exec("/root/bin/test.sh");
InputStreamReader ir = new InputStreamReader(process
.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null)
System.out.println(line);
input.close();
ir.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics