java执行Linux命令的方法

时间:2021-05-19

本文实例讲述了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程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章