java操作linux,調用shell命令

來源:互聯網
上載者:User

標籤:test   logger   path   sys   readline   rup   static   code   使用   

import org.junit.jupiter.api.Test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.util.logging.Level;import java.util.logging.Logger;public class Test001 {    public static String exec(String command) throws InterruptedException {        String returnString = "";        Process pro = null;        Runtime runTime = Runtime.getRuntime();        if (runTime == null) {            System.err.println("Create runtime false!");        }        try {            pro = runTime.exec(command);            BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream()));            PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));            String line;            while ((line = input.readLine()) != null) {                returnString = returnString + line + "\n";            }            input.close();            output.close();            pro.destroy();        } catch (IOException ex) {            Logger.getLogger(Test001.class.getName()).log(Level.SEVERE, null, ex);        }        return returnString;    }    @Test    public void test() throws Exception {        System.out.println(exec("ls -al"));    }}

mac同樣適用

調用shell指令碼,判斷是否正常執行,如果正常結束,Process的waitFor()方法返回0

public static void callShell(String shellString) {      try {          Process process = Runtime.getRuntime().exec(shellString);          int exitValue = process.waitFor();          if (0 != exitValue) {              log.error("call shell failed. error code is :" + exitValue);          }      } catch (Throwable e) {          log.error("call shell failed. " + e);      }  }

 

 

 

package test.shell;import java.io.BufferedReader;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;public class JavaShellUtil {    //基本路徑    private static final String basePath = "/tmp/";    //記錄Shell執行狀況的記錄檔的位置(絕對路徑)    private static final String executeShellLogFile = basePath + "executeShell.log";    //傳送檔案到Kondor系統的Shell的檔案名稱(絕對路徑)    private static final String sendKondorShellName = basePath + "sendKondorFile.sh";    public int executeShell(String shellCommand) throws IOException {        int success = 0;        StringBuffer stringBuffer = new StringBuffer();        BufferedReader bufferedReader = null;//格式化日期時間,記錄日誌時使用          DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");        try {            stringBuffer.append(dateFormat.format(new Date())).append("準備執行Shell命令 ").append(shellCommand).append(" \r\n");            Process pid = null;            String[] cmd = {"/bin/sh", "-c", shellCommand};            //執行Shell命令            pid = Runtime.getRuntime().exec(cmd);            if (pid != null) {                stringBuffer.append("進程號:").append(pid.toString()).append("\r\n");                //bufferedReader用於讀取Shell的輸出內容 bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);                pid.waitFor();            } else {                stringBuffer.append("沒有pid\r\n");            }            stringBuffer.append(dateFormat.format(new Date())).append("Shell命令執行完畢\r\n執行結果為:\r\n");            String line = null;            //讀取Shell的輸出內容,並添加到stringBuffer中            while (bufferedReader != null && (line = bufferedReader.readLine()) != null) {                stringBuffer.append(line).append("\r\n");            }        } catch (Exception ioe) {            stringBuffer.append("執行Shell命令時發生異常:\r\n").append(ioe.getMessage()).append("\r\n");        } finally {            if (bufferedReader != null) {                OutputStreamWriter outputStreamWriter = null;                try {                    bufferedReader.close();                    //將Shell的執行情況輸出到記錄檔中                    OutputStream outputStream = new FileOutputStream(executeShellLogFile);                    outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");                    outputStreamWriter.write(stringBuffer.toString());                } catch (Exception e) {                    e.printStackTrace();                } finally {                    outputStreamWriter.close();                }            }            success = 1;        }        return success;    }}  

 

 

更多資料:

http://www.cnblogs.com/shihaiming/p/5884859.html

http://www.jb51.net/article/69930.htm

 

java操作linux,調用shell命令

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.