Java執行外部程序并返回結果

mxf8 9年前發布 | 5K 次閱讀 Java

import java.io.*;

/**

  • 示例:執行進程并返回結果 */ public class ProcessExecutor {

    public static final int SUCCESS = 0; // 表示程序執行成功

    public static final String COMMAND = "java.exe -version"; // 要執行的語句

    public static final String SUCCESS_MESSAGE = "程序執行成功!";

    public static final String ERROR_MESSAGE = "程序執行出錯:";

    public static void main(String[] args) throws Exception {

     // 執行程序
     Process process = Runtime.getRuntime().exec(COMMAND);
    
     // 打印程序輸出
     readProcessOutput(process);
    
     // 等待程序執行結束并輸出狀態
     int exitCode = process.waitFor();
    
     if (exitCode == SUCCESS) {
         System.out.println(SUCCESS_MESSAGE);
     } else {
         System.err.println(ERROR_MESSAGE + exitCode);
     }
    

    }

    /**

    • 打印進程輸出 *
    • @param process 進程 */ private static void readProcessOutput(final Process process) { // 將進程的正常輸出在 System.out 中打印,進程的錯誤輸出在 System.err 中打印 read(process.getInputStream(), System.out); read(process.getErrorStream(), System.err); }

      // 讀取輸入流 private static void read(InputStream inputStream, PrintStream out) { try {

       BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
      
       String line;
       while ((line = reader.readLine()) != null) {
           out.println(line);
       }
      
      

      } catch (IOException e) {

       e.printStackTrace();
      

      } finally {

       try {
           inputStream.close();
       } catch (IOException e) {
           e.printStackTrace();
       }
      

      } } }</pre>

 本文由用戶 mxf8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!