JavaSE读写资源配置文件

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);
}

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"));
}
发布了460 篇原创文章 · 获赞 812 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/lianghecai52171314/article/details/105454177
今日推荐