设为首页 加入收藏

TOP

Java调用Linux命令两种方式的例子
2014-11-24 13:10:00 来源: 作者: 【 】 浏览:0
Tags:Java 调用 Linux 命令 方式 例子

下面是两个执行Linux命令的例子:


包含文件:
import java.io.InputStreamReader;
import java.io.LineNumberReader;


/**
* 执行shell命令
*String[] cmd = { "sh", "-c", "lsmod |grep linuxVmux" }或者
*String[] cmd = { "sh", "-c", "./load_driver.sh" }
*int tp = 1 返回执行结果 非1 返回命令执行后的输出
*/
public String runCommand(String[] cmd,int tp){
StringBuffer buf = new StringBuffer(1000);
String rt="-1";
try {
Process pos = Runtime.getRuntime().exec(cmd);
pos.waitFor();
if(tp==1){
if(pos.exitValue()==0){
rt="1";
}
}else{
InputStreamReader ir = new InputStreamReader(pos.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String ln="";
while ((ln =input.readLine()) != null) {
buf.append(ln+"
");
}
rt = buf.toString();
input.close();
ir.close();
}
} catch (java.io.IOException e) {
rt=e.toString();
}catch (Exception e) {
rt=e.toString();
}
return rt;
}
/**
* 执行简单命令
* String cmd="ls"
*int tp = 1 返回执行结果 非1 返回命令执行后的输出
*/
public String runCommand(String cmd,int tp){
StringBuffer buf = new StringBuffer(1000);
String rt="-1";
try {
Process pos = Runtime.getRuntime().exec(cmd);
pos.waitFor();
if(tp==1){
if(pos.exitValue()==0){
rt="1";
}
}else{
InputStreamReader ir = new InputStreamReader(pos.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String ln="";
while ((ln =input.readLine()) != null) {
buf.append(ln+"
");
}
rt = buf.toString();
input.close();
ir.close();
}
} catch (java.io.IOException e) {
rt=e.toString();
}catch (Exception e) {
rt=e.toString();
}
return rt;
}


=================================
上述函数放在一个类中,需要的时候直接调用。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android UI之Memu菜单 下一篇Java执行Linux命令并返回命令结果

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: