java執(zhí)行Linux命令的方法
本文實例講述了java執(zhí)行Linux命令的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
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();
}
}
其中參數(shù) cmd 為Linux命令。每次只能執(zhí)行一條命令。
1.Java Runtime.exec()注意事項:
① 永遠要在調用waitFor()方法之前讀取數(shù)據(jù)流
② 永遠要先從標準錯誤流中讀取,然后再讀取標準輸出流
2.最好的執(zhí)行系統(tǒng)命令的方法就是寫個bat文件或是shell腳本。
希望本文所述對大家的Java程序設計有所幫助。
相關文章
解決java.sql.SQLException:?validateConnection?false問題的方法匯總(最
這篇文章主要給大家介紹了關于解決java.sql.SQLException:?validateConnection?false問題的方法匯總,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2023-03-03Springmvc實現(xiàn)文件下載2種實現(xiàn)方法
這篇文章主要介紹了Springmvc實現(xiàn)文件下載2種實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03elasticsearch索引index之engine讀寫控制結構實現(xiàn)
這篇文章主要為大家介紹了elasticsearch索引index之engine讀寫控制結構實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04