java执行Linux命令的方法
本文实例讲述了java执行linux命令的方法。分享给大家供大家参考。具体实现方法如下:
public class streamgobbler extends thread {
inputstream is;
string type;
public streamgobbler(inputstream is, string type) {
this.is = is;
this.type = type;
}
public void run() {
try {
inputstreamreader isr = new inputstreamreader(is);
bufferedreader br = new bufferedreader(isr);
string line = null;
while ((line = br.readline()) != null) {
if (type.equals("error")) {
system.out.println("error :" + line);
} else {
system.out.println("debug:" + line);
}
}
} catch (ioexception ioe) {
ioe.printstacktrace();
}
}
}
private void shell(string cmd)
{
string[] cmds = { "/bin/sh", "-c", cmd };
process process;
try
{
process = runtime.getruntime().exec(cmds);
streamgobbler errorgobbler = new streamgobbler(process.geterrorstream(), "error");
streamgobbler outputgobbler = new streamgobbler(process.getinputstream(), "output");
errorgobbler.start();
outputgobbler.start();
try
{
process.waitfor();
}
catch (interruptedexception e)
{
e.printstacktrace();
}
}
catch (ioexception e)
{
e.printstacktrace();
}
}
其中参数 cmd 为linux命令。每次只能执行一条命令。
1.java runtime.exec()注意事项:
① 永远要在调用waitfor()方法之前读取数据流
② 永远要先从标准错误流中读取,然后再读取标准输出流
2.最好的执行系统命令的方法就是写个bat文件或是shell脚本。
希望本文所述对大家的java程序设计有所帮助。