Properties类与配置文件

48 篇文章 1 订阅
5 篇文章 0 订阅

Properties类与配置文件

1.1 Properties配置文件说明

Properties类对应.properties文件。文件内容是键值对,键值对之间使用"="或空格隔开。开头是"#"的表示注释

 

    Properties类在加载.properties文件时使用的iso8859-1的编码。所以这个文件中的中文要特殊处理:如果这个配置文件中有中文就必须要进行转义,使用native2ascii.exe命令操作:

native2ascii d:/my.properties d:/my2.properties

   

    使用Properties类中的load(InputStream) 方法可以加载配置文件,使用其中的store(OutputStream) 方法可以保存配置到指定文件。

 

    更多的信息可以看Properties类的API文档。

 

1.2 加载配置文件

public static void testLoadProperties() throws Exception {

    Properties properties = new Properties();

 

    InputStream in = new FileInputStream("E:/itcast/config.properties");

    properties.load(in); // 加载

    in.close();

 

    System.out.println(properties);

}

1.3 写配置文件

public static void testStoreProperties() throws Exception {

    // 准备配置信息

    Properties properties = new Properties();

    properties.setProperty("name", "李四");

    properties.setProperty("age", "20");

 

    // 准备

    OutputStream out = new FileOutputStream("d:/my.properties");

    String comments = "这是我的配置文件";

 

    // 写出去

    properties.store(out, comments);

    out.close();

}


1.4 使用Properties类

public class DBUtil {

   

    static Properties properties = new Properties();

   

    static{

       try {

           Class clazz = DBUtil.class;

           InputStreamReader fileReader =

           new InputStreamReader(clazz.getResourceAsStream("/db.properties"));

           properties.load(fileReader);

       } catch (IOException e) {

           e.printStackTrace();

       }

    }

    public static String getUserName(){

       String userName =properties.getProperty("userName");

       return userName;

    }

   

    public static String getPassword(){

       return properties.getProperty("password");

    }

    public static void main(String[] args) {

       System.out.println("用户名:"+ getUserName());

       System.out.println("密码: "getPassword());

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值