システムプロパティ
システムプロバティの列挙
方法1
1 import java.util.Properties; 2 3 public class Test { 4 public static void main(String[] args) { 5 Properties props = System.getProperties(); 6 7 props.list(System.out); 8 } 9 }
方法2
1 import java.util.Properties; 2 import java.util.Iterator; 3 4 public class Test2 { 5 public static void main(String[] args) { 6 Properties p = System.getProperties(); 7 for(Iterator i = p.keySet().iterator();i.hasNext();){ 8 String key = (String)i.next(); 9 System.out.println(key +"=" +System.getProperty(key)); 10 } 11 12 } 13 }
特定のシステムプロパティ値の確認
1 public class Test3 { 2 public static void main(String[] args) { 3 System.out.println(System.getProperty("os.name")); 4 } 5 }
$ java Test3 Mac OS X
どのように役にたつか
OSの実行環境によって挙動を変更する
1 public class Test4 { 2 public static void main(String[] args) { 3 String os = System.getProperty("os.name"); 4 5 if (os.indexOf("Mac")==0) { } 6 else if (os.indexOf("Windows")==0) { } 7 else if (os.indexOf("Linux")==0) { } 8 9 } 10 }
ファイルパスを指定する
現在の作業ディレクトリ下のtmpというディレクトリの絶対パスを文字列として得たい場合
1 public class Test5 { 2 public static void main(String[] args) { 3 String pass = System.getProperty("user.dir") +System.getProperty("file.separator") +"tmp"; 4 5 System.out.println(pass); 6 7 } 8 }
$ java Test5 /Users/rdera/Desktop/tmp
Mac OS X上で実行したのでファイル区切り文字は'/'が指定された。
System.out.getProperty("file.separator")
とすることで、Windows上でもファイル区切り文字が正しく指定される。