MENÙ

Esegui il comando esterno Java e ottieni 3 risultati

sommario

Java comando esternoEsegui 3 (Output standard, output di errore, codice di ritorno) ottieni il risultato

Java Questa sezione presenta programmi di esempio che avviano comandi e file eseguibili esterni come le shell batch.
Inoltre, contemporaneamente all'esecuzione del comando esterno, come valore restituito dal metodo.uscita standard,,uscita dell'errore,,codice di ritornoOttenere.

Normalmente, puoi avviare un comando esterno in Java utilizzando il seguente metodo.

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

Inoltre, per ottenere il valore restituito dal comando esterno avviato, utilizzarejava.lang.Process Di aspettare()Eseguire.

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

programma di esempio

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

Risultato dell'esecuzione

Esempio di esecuzione

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

Risultato dell'output

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をコピーしました!
sommario