MENU

Exécutez la commande externe Java et obtenez 3 résultats

table des matières

Java commande externeExécuter 3 (Sortie standard, sortie d'erreur, code retour) obtenir le résultat

Java Cette section présente des exemples de programmes qui lancent des commandes et des fichiers exécutables externes tels que des shells batch.
De plus, en même temps que l'exécution de la commande externe, la valeur de retour de la méthode est utilisée.sortie standard,,sortie d'erreur,,Code de retourobtenir.

Normalement, vous pouvez lancer une commande externe en Java en utilisant la méthode suivante.

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

Aussi, pour obtenir la valeur de retour de la commande externe lancée, utilisezjava.lang.Processus de attendre()Exécuter.

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

exemple de programme

/**
 * 外部コマンドを実行します。
 * またリタンーン値で、標準出力、エラー出力 、リターンコードを取得します。
 * 例:
 *     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();
        }
    }
}

Résultat de l'exécution

Exemple d'exécution

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

Résultat de sortie

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をコピーしました!
table des matières