您当前的位置: 首页 >  Java

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

JavaSE读写属性文件

梁云亮 发布时间:2020-04-11 16:03:44 ,浏览量:2

简介

属性文件指的是项目中专门用来存放项目配置信息的文件,其后缀一般为.properties。 属性文件也叫资源配置文件

Properties读写属性文件 示例:写属性文件
public static void main(String[] args) throws IOException {
    Properties properties = new Properties();
    Writer writer = new FileWriter(new File("E:/abc.propertiest"));
    properties.setProperty("url","jdbc:mysql:///db_test");
    properties.setProperty("user","root");
    properties.setProperty("pasword","root");
    properties.store(writer, "haha");
    writer.close();
}
示例:读属性文件
public static void main(String[] args) throws IOException {
    Properties properties = new Properties();

    Reader reader = new FileReader(new File("E:/abc.propertiest"));
    properties.load(reader);

    String url = properties.getProperty("url");
    System.out.println(url);
    String user = properties.getProperty("user2");
    System.out.println(user);
    String password = properties.getProperty("password2","default");
    System.out.println(password);
}
示例:java Web项目中读取Properties 文件(★★★★★)
static  {
    Properties properties = new Properties();

    InputStream is =类名.class.getResourceAsStream("/abc.properties"));
    properties.load(is);

    String url = properties.getProperty("url");
    System.out.println(url);
    String user = properties.getProperty("user2");
    System.out.println(user);
    String password = properties.getProperty("password2","default");
    System.out.println(password);
}

注意:这种方式除了可以在JavaWEB中使用,也可以在JavaSE中使用,实际开发时建议使用这种方式。

ResourceBundle读取配置文件

第一步:在resources/目录下创建属性文件mysql.properties:

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_test?useSSL=false&serverTimezone=UTC
username=root
password=root

第二步:编写读取属性的工具类:

public class PropertiesUtil {
    private static Map valueMap = new HashMap();
    static {
        // 国际化
        ResourceBundle ct = ResourceBundle.getBundle("mysql");  //注意此处,只需文件名而不需要文件后缀
        Enumeration enums = ct.getKeys();
        while ( enums.hasMoreElements() ) {
            String key = enums.nextElement();
            String value = ct.getString(key);
            valueMap.put(key, value);
        }
    }
    public static String getValue(String key ) {
        return valueMap.get(key);
    }
}
	测试代码:
public static void main(String[] args) {
    System.out.println(PropertiesUtil.getValue("driver"));
}
关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0475s