danglingfarpointer's memoization

仕事周りでの気付き、メモ、愚痴などを書いていきます。

Javaから外部コマンド起動

Javaから外部コマンドを起動するサンプルプログラム。

import java.io.File;
import java.io.IOException;

public class ProcessRunner {
    public static int exec(String exePath, String dir) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder(exePath);
        pb.directory(new File(dir));
        
        Process p = pb.start();
        return p.waitFor();
    }
    
    public static void main(String[] args) throws IOException, InterruptedException {
        String exePath = "/Users/foo/main"; // 実行ファイル
        String dir = "/Users/foo/temp"; // 実行場所
        System.out.println("ret val:" + exec(exePath, dir));
    }
}

標準出力を取得しようとすると、少し面倒になる。ファイルで一旦受け取るようにしたほうが便利か。

(参考) http://www.ne.jp/asahi/hishidama/home/tech/java/process.html

ついでに、Javaから呼び出されるc++のサンプルプログラム(あくまで内容は適当)

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

// あるファイルの行数を返すc++プログラム
int main()
{
    string filename = "foo.txt";
    ifstream ifs((filename.c_str()));
    if(!ifs.is_open()){
        cerr << ">>> cannot open " << filename << endl;
        return -1;
    }

    int i = 0;
    while(!ifs.eof()){
        string s;
        getline(ifs, s);
        ++i;
    }

    return i;
}