【Properties文件】Java使用Properties来读取配置文件
原创
©著作权归作者所有:来自51CTO博客作者刘林VIP的原创作品,请联系作者获取转载授权,否则将追究法律责任
配置文件位置及内容
执行结果
程序代码
package Utils.ConfigFile;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
public class PropertiesTest {
/**
* 获取属性文件
* @param path 属性文件路径
* @return
*/
public static Properties getPropsFile(String path) {
Properties props = new Properties();
try {
File file = new File(path);
InputStream in = new BufferedInputStream(new FileInputStream(file));
//解决中午乱码问题--因为字节流无法读取中文,所以采用reader把inputStream转换成reader用字符流来读取中文
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
props.load(bf);
in.close();
} catch (Exception e) {
return null;
}
return props;
}
/**
* 显示所有键值
* @param properties
*/
public static void showKeys(Properties properties){
Enumeration<?> enumeration = properties.propertyNames();
System.out.println("======下面将显示所有key值============");
while(enumeration.hasMoreElements()){
Object key = enumeration.nextElement();
System.out.println(key);
}
}
/**
* 显示所有value值
* @param properties
*/
public static void showValues(Properties properties){
Enumeration<?> enumeration = properties.elements();
System.out.println("======下面将显示所有value值============");
while(enumeration.hasMoreElements()){
Object value = enumeration.nextElement();
System.out.println(value);
}
}
/**
* 显示所有key,value
* @param properties
*/
public static void showKeysAndValues(Properties properties){
Iterator<Map.Entry<Object, Object>> it= properties.entrySet().iterator();
System.out.println("======下面将显示所有<key,value>值---方式1============");
while (it.hasNext()) {
Map.Entry<Object, Object> entry = it.next();
Object key = entry.getKey().toString();
Object value = entry.getValue();
System.out.println("<" + key + "," + value + ">");
}
}
/**
* 显示所有key,value
* @param properties
*/
public static void showKeysAndValues2(Properties properties){
System.out.println("======下面将显示所有<key,value>值--方式2============");
for (Map.Entry<Object, Object> entry: properties.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println("<" + key + "," + value + ">");
}
}
public static void main(String args[]) {
Properties propFile = getPropsFile("C:\\myProperties.properties");
showKeys(propFile);
showValues(propFile);
showKeysAndValues(propFile);
showKeysAndValues2(propFile);
}
}