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
本文介绍了一个简单的Java程序,用于从配置文件中读取属性,并提供了完整的代码示例及运行结果。程序通过FileInputStream打开指定路径的配置文件,使用Properties类加载文件内容,并按键获取相应的值。
1万+

被折叠的 条评论
为什么被折叠?



