Java java.langパッケージのRuntimeクラス
Runtimeクラスは、実行環境をオブジェクト化するために使用する。Runtimeオブジェクトを利用すると、現在のオペレーティングシステムとの相互作用が可能である。JVM(Java仮想マシン)が動作するシステムとのインターフェースを提供し、JavaクラスではないOSベースのプログラムを実行したり、OSに関する情報を提供したりする。
Runtimeの主なメソッド
| メソッド | 説明 |
|---|---|
Process exec(String command) |
命令(command)を実行し、実行したプロセスの参照を返す。 |
static Runtime getRuntime() |
Runtimeオブジェクトの参照を返す。 |
void exit(int status) |
状態値(status)を返しながらJVMを終了させる。 |
long freeMemory() |
JVMが使用可能なメモリ量(bytes)を返す。 |
long totalMemory() |
JVMが使用している全メモリを返す。 |
long maxMemory() |
JVMが使用できる最大メモリ量を返す。 |
Runtimeの例
例 1)
package com.devkuma.tutorial.java.lang;
public class RuntimeClass {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
long totalMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
long usedMemory = totalMemory - freeMemory;
System.out.println("Total Memory : " + totalMemory);
System.out.println("Free Memory : " + freeMemory);
System.out.println("Used Memory : " + usedMemory);
}
}
実行結果は以下のとおりである。
Total Memory : 128974848
Free Memory : 126929960
Used Memory : 2044888
例 2) 以下の例では、該当するOSのコードだけを記述する。すべて実行するとエラーが発生する。
package com.devkuma.tutorial.javalang;
import java.io.IOException;
public class RuntimeClass1 {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
// Macの場合、以下の命令を実行する。
try {
runtime.exec("open /Applications/Contacts.app");
} catch (IOException e) {
System.err.println("Error executing Contacts.");
}
// linuxの場合、以下の命令を実行する。
try {
runtime.exec("gedit");
} catch (IOException e) {
System.err.println("Error executing gedit.");
}
// windowsの場合、以下の命令を実行する。
try {
runtime.exec("calc.exe");
} catch (IOException e) {
System.err.println("Error executing calc.");
}
}
}
実行すると各OSに合ったアプリケーションプログラムが実行される。実行結果は省略する。
参照
http://itmore.tistory.com/entry/Runtime-%ED%81%B4%EB%9E%98%EC%8A%A4