下面是一個例子,演示如何執行一個進程(類似于在命令行下鍵入命令),讀取進程執行的輸出,并根據進程的返回值判斷是否執行成功。一般來說,進程返回 0 表示執行成功,其他值表示失敗。

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();
            }
        }
    }
}