JavaSE读写属性文件

66 篇文章 6 订阅

简介

属性文件指的是项目中专门用来存放项目配置信息的文件,其后缀一般为.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<String, String> valueMap = new HashMap<>();
    static {
        // 国际化
        ResourceBundle ct = ResourceBundle.getBundle("mysql");  //注意此处,只需文件名而不需要文件后缀
        Enumeration<String> 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"));
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梁云亮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值