java履行Linux敕令的辦法。本站提示廣大學習愛好者:(java履行Linux敕令的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是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法式設計有所贊助。