Properties读取配置文件的两种方式

首先是 通过FileInputStream,通过绝对路劲的方法获得。
public static Properties getProperties(){
InputStream inputStream;
Properties properties=null;
try {
inputStream = new FileInputStream("D:\\workspace\\Commons-IO_Test\\src\\main\\resources\\mysqlNamePassword.properties");
properties=new Properties();
properties.load(inputStream);

} catch (IOException e) {
e.printStackTrace();
}
finally{
return properties;
}
}

第二种是通过JDBCText.class.getClassLoader().getResourceAsStream("mysqlNamePassword.properties");

JDBCText是我创建的类

getClassLoader()是类加载器


getResourceAsStream是获得resources里面的资源并且是以流的形式

public static Properties getProperties(){
Properties properties=new Properties();
InputStream inStream=null;
try{
inStream=JDBCText.class.getClassLoader().getResourceAsStream("mysqlNamePassword.properties");
properties.load(inStream);
}finally{
return properties;
}

}
其中都是用 load方法把读取的文件内容以键值对的方式传入properties对象中,文件内容一定要是

name=test
age=18
这种格式
不能加双引号,单引号

猜你喜欢

转载自www.cnblogs.com/xuzhiwen/p/11610949.html