java解析cfg.properties属性文件

       properties是一种属性文件 , 这种文件以key=value格局存储内容 。 Java中可以利用java.util.Properties类来读取这个文件 , 按照左边的key获取值 , String value=https://vvvtt.com/article/p.getProperty(key);
       多种解析属性文件的体例中java.util.Properties解析文件的体例是同一的 , 都是经由过程load加载InputStream 对象 。 本家儿如果获取InputStream 对象的体例分歧 , 现实利用中我们不一定能精确获取properties属性文件的绝对路径 。
      属性文件在eclipse和IDEA没有安装插件的环境下展示时会将中文转为Unicode编码 , eclipse选中内容F2会显示具体的中文内容(如下图) 。

java解析cfg.properties属性文件

文章插图

需要这些哦
电脑
eclipse或者intellij IDEA
第一
:properties属性文件解析体例1第一种:本家儿如果经由过程class.getClassLoader().getResourceAsStream
1、是实现获取在classpath路径下的资本文件的输入流
为什么是classpath而不是src , 因为当web项目运行时,IDE编译器会把src下的一些资本文件移至WEB-INF/classes , classPath目次其实就是这个classes目次 。 这个目次下放的一般是web项目运行时的class文件、资本文件(xml,properties...);
2、本家儿要代码:
import java.io.IOException;
【java解析cfg.properties属性文件】import java.io.InputStream;
import java.util.Properties;
public class PropertiesUtils {
/**
* 按照key获取cfg.properties的值

* @param key
* @return
*/
public static String getCfgPropertiesValue(String key) {
Properties pro = new Properties();
InputStream is = null;
try {
is = PropertiesUtils.class.getClassLoader().getResourceAsStream(
"CodeMapping.properties");
System.out.println();
// 读取属性文件
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return pro.getProperty(key);
}
}
3、main方式测试成果
public class Test5 {
public static void main(String[] args) {
System.out.println("name:"
+ PropertiesUtils.getCfgPropertiesValue("name"));
}
}

java解析cfg.properties属性文件

文章插图

java解析cfg.properties属性文件

文章插图

2第二种:经由过程class.getResourceAsStream(String name)获取 。
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Test5 {
public static void main(String[] args) {
System.out.println("name:" + getCfgPropertiesValue("name"));
}
/**
* 按照key获取CodeMapping.properties的值
* @param key
* @return
*/
public static String getCfgPropertiesValue(String key) {
Properties pro = new Properties();
InputStream is = null;
try {
is = Test5.class
.getResourceAsStream("/CodeMapping.properties");
System.out.println();
// 读取属性文件
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return pro.getProperty(key);

推荐阅读