valueOf方法擷取的是字元串本身能轉化的數值,getInteger方法擷取的是系統屬性對應的數值。
(這裡的系統屬性是指java通過system.getproperty獲得的環境變量,如作業系統配置資訊以及軟體資訊。
有關系統屬性可以參考:http://blog.csdn.net/babydavic/article/details/1755718)
平常開發中,字元串轉整數用valueOf方法。getInteger方法能不用則不要用。兩者完全不一樣。
@Test
public void Test0(){
String s = "123";
Integer getInt = Integer.getInteger(s);
Integer valueOf = Integer.valueOf(s);
System.out.println("Integer.getInteger(\""+ s + "\")=" + getInt);
System.out.println("Integer.valueOf(\""+ s + "\")=" + valueOf);
}
輸出結果:
Integer.getInteger("123")=null
Integer.valueOf("123")=123
深入了解getInteger方法:擷取系統屬性的方法:System.getProperties()
@Test
public void Test(){
Properties prop = System.getProperties();
Enumeration keys = prop.keys();
while(keys.hasMoreElements()){
String s = keys.nextElement().toString();
Integer i = Integer.getInteger(s);
System.out.println(s + "=" + i);
}
}
輸出結果:我的jdk下隻有系統屬性sun.arch.data.model可轉換為相應的Integer對象
java.runtime.name=null
sun.boot.library.path=null
java.vm.version=null
java.vm.vendor=null
java.vendor.url=null
path.separator=null
java.vm.name=null
file.encoding.pkg=null
user.country=null
sun.java.command=null
java.home=null
...
sun.arch.data.model=64
...
普通的屬性檔案不能輸出對應的Integer值:這裡用資料庫配置檔案jdbc.properties做個測試
@Test
public void Test2(){
try{
BufferedReader br = new BufferedReader(new FileReader("config/jdbc.properties"));
Properties p = new Properties();
p.load(br);
Enumeration keys = p.keys();
while(keys.hasMoreElements()){
String s = keys.nextElement().toString();
Integer i = Integer.getInteger(s);
System.out.println(s + "=" + i);
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
輸出結果全是null:
jdbc.maintenanceInterval=null
portNumber.base=null
jdbc.loginTimeout=null
jdbc.maxPoolSize=null
jdbc.minPoolSize=null
databaseName.base=null
uniqueResourceName.base=null
jdbc.borrowConnectionTimeout=null
jdbc.xaDataSourceClassName=null
jdbc.maxIdleTime=null
jdbc.poolSize=null
jdbc.logWriter=null
...
将普通屬性添加到系統屬性,則可以通路到該屬性值:添加到系統屬性的方法:System.setProperties(p)
@Test
public void Test3(){
try{
BufferedReader br = new BufferedReader(new FileReader("config/jdbc.properties"));
Properties p = new Properties();
p.load(br);
System.setProperties(p);
Enumeration keys = p.keys();
while(keys.hasMoreElements()){
String s = keys.nextElement().toString();
Integer i = Integer.getInteger(s);
System.out.println(s + "=" + i);
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
輸出結果:根據jdbc對應的屬性名列印屬性值,能轉化成Integer型的則輸出了數值,不能轉化成Integer型的則輸出null
jdbc.maintenanceInterval=60
portNumber.base=5432
jdbc.loginTimeout=60
jdbc.maxPoolSize=500
jdbc.minPoolSize=5
databaseName.base=null
uniqueResourceName.base=null
jdbc.borrowConnectionTimeout=60
jdbc.xaDataSourceClassName=null
jdbc.maxIdleTime=60
jdbc.poolSize=5
jdbc.logWriter=60
...
最後:不要被兩個方法的表面意思類似迷惑了,老老實實用valueOf方法吧。雖然知道了getInteger的一些用法,但是對本人目前來說,還是覺得沒什麼用。。。算是漲姿勢吧,說不定哪天用上了。。。