Java中读取properties文件的两种方式

来源:互联网 发布:淘宝代收货怎么弄 编辑:程序博客网 时间:2024/05/07 09:01

在Javaweb开发中,通常会把数据库的配置文件等信息写到db.properties文件中,目的是为了解耦,可以在不更改源码的条件下切换数据库

在Java中读取db.properties文件通常有两种方式


db.properties配置文件

username=zhangsanpassword=liuli123456

方式1、

public class One{public static void main(String []args) throws Exception{InputStream input = new FileInputStream("db.properties");FileOutputStream out = new FileOutputStream("D:\\aaa.properties");Properties prop = new Properties();prop.load(input);System.out.println(prop.getProperty("username"));System.out.println(prop.getProperty("password"));prop.setProperty("name","value");//设置属性值prop.store(out,"aaaaaaa");//写入FileOutputStream所关联的文件,"aaaaaa"是注释信息}}


方式2、

public class two{public static void main(String []args) throws Exception{Properties prop = new Properties();prop.load(two.class.getClassLoader().getResourceAsStream("db.properties")); //类加载器,在本类下 System.out.println(prop.getProperty("username"));System.out.println(prop.getProperty("password"));}}


0 0