2009-06-23

Java : Process を使ってコマンドを実行したい


Java で Process を使ってコマンドを実行したい ... とか思ってはいない



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


public class Sample {

    public static void main(String[] args) {
        execute1("ipconfig");
        execute2("ipconfig");
    }

    private static void execute1(String command) {
        System.out.println("::: ProcessBuilder :::::");
        Process p = null;
        try {
            p = new ProcessBuilder(command).start(); 
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (p == null) {
            return ;
        }
        InputStream is = p.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try { is.close(); } catch (IOException e) {}
            }
            if (p != null) {
                p.destroy();
            }
        }
    }

    private static void execute2(String command) {
        System.out.println("::: Runtime :::::");
        Runtime r = Runtime.getRuntime();
        Process p = null;
        try {
            p = r.exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (p == null) {
            return ;
        }
        InputStream is = p.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try { is.close(); } catch (IOException e) {}
            }
            if (p != null) {
                p.destroy();
            }
        }
    }
}



ぐだぐだ。
こんなことしたかったんじゃないんだ。



環境
java : jdk160_05(JDev11g 付属)
OS : Windows XP Pro sp2

0 件のコメント:

コメントを投稿