本文實例講述了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程式設計有幫助。