LoginSignup
40
41

More than 5 years have passed since last update.

Javaで外部プロセス実行(システムコール)を行う

Last updated at Posted at 2016-11-10

Javaで外部プロセス実行(システムコール)を行う

目的

  • Java アプリケーションから外部プロセスを実行する
  • 外部プロセスを実行した結果を取得する

実行環境

  • OS:Windows 7
  • 言語:Java 8
  • 開発環境:eclipse
  • 今回呼び出す外部プロセス:notepad, mecab

外部プロセスを実行する(サンプル:メモ帳を起動する)

メモ帳が起動したら成功

SystemCall.java

SystemCall.java
import java.io.IOException;


public class SystemCall {

    public static void main(String[] args) {
        String[] Command = { "cmd", "/c", "notepad.exe"}; // 起動コマンドを指定する
        Runtime runtime = Runtime.getRuntime(); // ランタイムオブジェクトを取得する
            try {
                runtime.exec(Command); // 指定したコマンドを実行する
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

}

外部プロセスを実行した結果を取得する(サンプル:mecabで形態素解析を行った結果を取得する)

SystemCall2.java

SystemCall2.java
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class SystemCall2 {

    public static void main(String[] args) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        String analysisFilePath = "C:/Users/suzuki_y/Documents/analysisObject.txt"; // mecabで形態素解析したいtxtファイルを指定

        String[] Command = { "cmd", "/c", "mecab.exe " + analysisFilePath }; // cmd.exeでmecab.exeを起動し指定したファイル(filePath)を形態素解析する

        Process p = null;
        File dir = new File("C:/Program Files (x86)/MeCab/bin");// 実行ディレクトリの指定
        try {
            p = runtime.exec(Command, null, dir); // 実行ディレクトリ(dir)でCommand(mecab.exe)を実行する
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            p.waitFor(); // プロセスの正常終了まで待機させる
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        InputStream is = p.getInputStream(); // プロセスの結果を変数に格納する
        BufferedReader br = new BufferedReader(new InputStreamReader(is)); // テキスト読み込みを行えるようにする

        while (true) {
            String line = br.readLine();
            if (line == null) {
                break; // 全ての行を読み切ったら抜ける
            } else {
                System.out.println("line : " + line); // 実行結果を表示
            }
        }
    }
}
40
41
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
41