MENÚ

Ejecute el comando externo de Java y obtenga 3 resultados

Tabla de contenido

Java comando externoEjecute 3 (Salida estándar, salida de error, código de retorno) obtener el resultado

Java Esta sección presenta programas de ejemplo que ejecutan comandos y archivos ejecutables externos, como shells por lotes.
Además, al mismo tiempo que se ejecuta el comando externo, como valor de retorno del método.salida estándar,,salida de error,,código de retornoconseguir.

Normalmente, puede ejecutar un comando externo en Java utilizando el siguiente método.

Runtime r = Runtime.getRuntime();
r.exec("実行するコマンド名");

Además, para obtener el valor de retorno del comando externo iniciado, utilicejava.lang.Proceso de esperar()Ejecutar.

Process p = Runtime.getRuntime().exec("実行するコマンド名");
int ret = p.waitFor()

programa de muestra

/**
 * 外部コマンドを実行します。
 * またリタンーン値で、標準出力、エラー出力 、リターンコードを取得します。
 * 例:
 *     execCommand("notepad.exe");
 *
 * @see execCommand(String[] cmds)
 *    ※実行するコマンドに引数(パラメータ)がある場合は、
 *    以下を使用してください。
 * @param cmd 実行するコマンド
 * @return コマンド実行結果情報を保持するString配列
 *    配列[0] ⇒ 標準出力
 *    配列[1] ⇒ エラー出力
 *    配列[2] ⇒ リターンコード
 * @throws IOException 入出力エラーが発生した場合
 */
public static String[] execCommand(String cmd) throws IOException,
        InterruptedException {
    return execCommand(new String[] { cmd });
}
/**
 * 外部コマンドを引数(パラメータ)を指定して実行します。
 * またリタンーン値で、標準出力、エラー出力 、リターンコードを取得します。
 * 例:
 *     execCommand(new String[]{"notepad.exe","C:\test.txt"});
 *
 * Process.waitFor()を実行していますので、外部コマンドの実行が
 * 終了するまでこのメソッドは待機します。
 *
 * @see execCommand(String cmd)
 *    ※実行するコマンドに引数がない場合は簡易的にこちらを
 *      使用してください。
 * @param cmds 実行するコマンドと引数を含む配列
 * @return コマンド実行結果情報を保持するString配列
 *    配列[0] ⇒ 標準出力
 *    配列[1] ⇒ エラー出力
 *    配列[2] ⇒ リターンコード
 * @throws IOException 入出力エラーが発生した場合
 */
public static String[] execCommand(String[] cmds) throws IOException,
                                                    InterruptedException {
    String[] returns = new String[3];
    String LINE_SEPA = System.getProperty("line.separator");
    Runtime r = Runtime.getRuntime();
    Process p = r.exec(cmds);
    InputStream in = null;
    BufferedReader br = null;
    try {
        in = p.getInputStream();
        StringBuffer out = new StringBuffer();
        br = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = br.readLine()) != null) {
            out.append(line + LINE_SEPA);
        }
        returns[0] = out.toString();
        br.close();
        in.close();
        in = p.getErrorStream();
        StringBuffer err = new StringBuffer();
        br = new BufferedReader(new InputStreamReader(in));
        while ((line = br.readLine()) != null) {
            err.append(line + LINE_SEPA);
        }
        returns[1] = err.toString();
        returns[2] = Integer.toString(p.waitFor());
        return returns;
    } finally {
        if (br != null) {
            br.close();
        }
        if (in != null) {
            in.close();
        }
    }
}

Resultado de la ejecución

Ejemplo de ejecución

public static void main(String[] args) {
    try {
	    System.out.println("1. 引数なしで実行。※helpコマンドを実行。");
	    String[]s = execCommand("help");
	    System.out.println(
	            "\n[標準出力]\n"+s[0].substring(0,200)+
	            "\n[エラー出力]\n"+s[1]+
	            "\n[リターンコード]\n"+s[2] + "\n\n");
	    
	    System.out.println("2. 引数を指定して実行。※helpコマンドの引数にdirを指定して実行。");
	    s = execCommand(new String[]{"help","dir"});
	    System.out.println(
	            "\n[標準出力]\n"+s[0].substring(0,200)+
	            "\n[エラー出力]\n"+s[1]+
	            "\n[リターンコード]\n"+s[2] + "\n\n");
	    
	    System.out.println("3. バッチファイルを実行。※さらにリターンコードを評価して処理を分岐する。");		    
	    s = execCommand("C:\\test.bat");
	    if (!s[2].equals("0")) {
	        System.out.println("\ntest.batは異常終了しています。[リターンコード]="+s[2]);
	    }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Resultado de salida

1. 引数なしで実行。※helpコマンドを実行。
[標準出力]
特定のコマンドの詳細情報は、"HELP コマンド名" を入力してください
ASSOC    ファイル拡張子の関連付けを表示または変更します。
ATTRIB   ファイルの属性を表示または変更します。
BREAK    拡張 CTRL+C チェックを設定または解除します。
BCDEDIT  ブート データベースのプロパティを設定して起動時の読み込みを制御します。
CACLS    ファイル
[エラー出力]

[リターンコード]
1


2. 引数を指定して実行。※helpコマンドの引数にdirを指定して実行。
[標準出力]
ディレクトリ中のファイルとサブディレクトリを一覧表示します。

DIR [ドライブ:][パス][ファイル名] [/A[[:]属性]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]ソート順]] [/P] [/Q] [/R] [/S] [/T[[:]タイムフィールド]] [/W] [/X] [/4]

  [ドライブ:][パス][ファイル名]
           
[エラー出力]

[リターンコード]
1


3. バッチファイルを実行。※さらにリターンコードを評価して処理を分岐する。
test.batは異常終了しています。[リターンコード]=9
echo test.batが実行されました。
echo エラーが発生しています。
exit 9
  • URLをコピーしました!
Tabla de contenido