java執(zhí)行Linux命令的方法
本文實(shí)例講述了java執(zhí)行Linux命令的方法。分享給大家供大家參考。具體實(shí)現(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()注意事項(xiàng):
① 永遠(yuǎn)要在調(diào)用waitFor()方法之前讀取數(shù)據(jù)流
② 永遠(yuǎn)要先從標(biāo)準(zhǔn)錯(cuò)誤流中讀取,然后再讀取標(biāo)準(zhǔn)輸出流
2.最好的執(zhí)行系統(tǒng)命令的方法就是寫個(gè)bat文件或是shell腳本。
希望本文所述對大家的Java程序設(shè)計(jì)有所幫助。
相關(guān)文章
解決java.sql.SQLException:?validateConnection?false問題的方法匯總(最
這篇文章主要給大家介紹了關(guān)于解決java.sql.SQLException:?validateConnection?false問題的方法匯總,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03關(guān)于springboot中的自定義配置項(xiàng)
這篇文章主要介紹了關(guān)于springboot中的自定義配置項(xiàng),在項(xiàng)目開發(fā)的過程中,經(jīng)常需要自定義系統(tǒng)業(yè)務(wù)方面的配置文件及配置項(xiàng),Spring Boot提供了@value注解、@ConfigurationProperties注解和Environment接口等3種方式自定義配置項(xiàng),需要的朋友可以參考下2023-07-07Springmvc實(shí)現(xiàn)文件下載2種實(shí)現(xiàn)方法
這篇文章主要介紹了Springmvc實(shí)現(xiàn)文件下載2種實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03elasticsearch索引index之engine讀寫控制結(jié)構(gòu)實(shí)現(xiàn)
這篇文章主要為大家介紹了elasticsearch索引index之engine讀寫控制結(jié)構(gòu)實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04