java执行Linux命令的方法
本文实例讲述了java执行Linux命令的方法。分享给大家供大家参考。具体实现方法如下:
publicclassStreamGobblerextendsThread{
InputStreamis;
Stringtype;
publicStreamGobbler(InputStreamis,Stringtype){
this.is=is;
this.type=type;
}
publicvoidrun(){
try{
InputStreamReaderisr=newInputStreamReader(is);
BufferedReaderbr=newBufferedReader(isr);
Stringline=null;
while((line=br.readLine())!=null){
if(type.equals("Error")){
System.out.println("Error :"+line);
}else{
System.out.println("Debug:"+line);
}
}
}catch(IOExceptionioe){
ioe.printStackTrace();
}
}
}
privatevoidshell(Stringcmd)
{
String[]cmds={"/bin/sh","-c",cmd};
Processprocess;
try { process=Runtime.getRuntime().exec(cmds);
StreamGobblererrorGobbler=newStreamGobbler(process.getErrorStream(),"Error"); StreamGobbleroutputGobbler=newStreamGobbler(process.getInputStream(),"Output"); errorGobbler.start(); outputGobbler.start(); try { process.waitFor(); } catch(InterruptedExceptione) { e.printStackTrace(); } } catch(IOExceptione) { e.printStackTrace(); } }
热门推荐
10 牛年大气简短的祝福语
11 晚来的生日祝福语简短
12 俄语随口祝福语简短版
13 妈妈的中考祝福语简短
14 生日祝福语简短霸气男
15 爸爸寿宴仪式祝福语简短
16 过年红包祝福语简短霸气
17 毕业祝福语老婆生日简短
18 文案生日祝福语高级简短