import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class TestProperty {
private Properties propertie;
private FileInputStream inputFile;
/**
* @param filePath
* 要讀取的配置文件的路徑 名稱
*/
public void initProperty(String filePath) {
propertie = new Properties();
try {
inputFile = new FileInputStream(filePath);
propertie.load(inputFile);
inputFile.close();
} catch (FileNotFoundException ex) {
System.out.println("讀取屬性文件-失敗!- 原因:文件路徑錯誤或者文件不存在");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("裝載文件-失敗!");
ex.printStackTrace();
}
}
/**
*
* @param key
* 根據鍵獲取對應的值
* @return
*/
public String getPropertyValue(String key) {
if (propertie.containsKey(key)) {
String value = propertie.getProperty(key);
return value;
} else {
return null;
}
}
public static void main(String args[]) {
TestProperty t = new TestProperty();
t.initProperty("C:\\test\\config.properties");
String base=t.getPropertyValue("base");
String step=t.getPropertyValue("step");
System.out.println("base="+base);
System.out.println("step="+step);
}
}
輸出結果:
base=50
step=10
config.properties文件內容:
base=50
step=10