码迷,mamicode.com
首页 > 编程语言 > 详细

Java读取配置文件

时间:2017-07-26 23:41:02      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:input   .class   使用   blog   stat   配置   string   文件   调试   

在src目录下新建配置文件test.properties

  格式为:key=value

  内容为:name=louis  

读取方式1:

  public static void props1() throws Exception {
        //没调试成功,找不到文件
        //Reader read = new FileReader("/db.properties");
        //成功,默认找相对路径,如果加/,则从根目录开始找
        //InputStream read = propertiesDemo.class.getResourceAsStream("/db.properties");
        //成功,从根目录开始找
        InputStream read = propertiesDemo.class.getClassLoader().getResourceAsStream("db.properties");
        Properties props = new Properties();
        props.load(read);

        String s = props.getProperty("driver");
        System.out.println(s);
    }

读取方式2:

    public static void props2() {
        //不用加.properties
        ResourceBundle rb = ResourceBundle.getBundle("db");
        String d = rb.getString("driver");
        System.out.println(d);
    }

 

在配置文件中,中文会自动转成Unicode码,可以设置默认编码为utf-8

 

使用配置文件,可以将一些数据写到配置文件中,如数据库连接的数据。

Java读取配置文件

标签:input   .class   使用   blog   stat   配置   string   文件   调试   

原文地址:http://www.cnblogs.com/liuyz/p/7241956.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!