Java如何读取和写入Properties属性文件
在本Java教程中,我们将学习使用Properties.load()方法读取属性文件。同时,我们将使用Properties.setProperty()方法将新的属性写入.properties文件。
1.设置
以下是我们将在示例中使用的属性文件。
firstName=Lokesh lastName=Gupta blog=panizye.com technology=java
2.读取属性文件
在大多数应用程序中,属性文件在应用程序启动时加载,并被缓存以供将来引用。无论何时我们需要获取属性的值,我们都会参考属性缓存并从中获取值。
属性缓存通常是一个单例静态实例,以便应用程序不需要多次读取属性文件;因为对于任何时间敏感的应用程序来说,再次读取文件的IO成本非常高。
示例1:在Java中读取.properties文件
在给定的示例中,我们从位于类路径中的app.properties文件中读取属性。类PropertiesCache充当已加载属性的缓存。
文件懒加载,但仅加载一次。
public class PropertiesCache { private final Properties configProp = new Properties(); private PropertiesCache() { //Private constructor to restrict new instances InputStream in = this.getClass().getClassLoader().getResourceAsStream("application.properties"); System.out.println("Reading all properties from the file"); try { configProp.load(in); } catch (IOException e) { e.printStackTrace(); } } //Bill Pugh Solution for singleton pattern private static class LazyHolder { private static final PropertiesCache INSTANCE = new PropertiesCache(); } public static PropertiesCache getInstance() { return LazyHolder.INSTANCE; } public String getProperty(String key){ return configProp.getProperty(key); } public Set<String> getAllPropertyNames(){ return configProp.stringPropertyNames(); } public boolean containsKey(String key){ return configProp.containsKey(key); } }
在上面的代码中,我们使用了Bill Pugh的技术来创建单例实例。
让我们测试上面的代码。
public static void main(String[] args) { //获取Properties对象中的单个属性 System.out.println(PropertiesCache.getInstance().getProperty("firstName")); System.out.println(PropertiesCache.getInstance().getProperty("lastName")); //获取所有属性名称 System.out.println(PropertiesCache.getInstance().getAllPropertyNames()); }
输出:
Read all properties from file Lokesh Gupta [lastName, technology, firstName, blog]
3.写入属性文件
就我个人而言,我没有找到从应用程序代码修改属性文件的任何好理由。只有在准备数据以供导出到第三方供应商/或需要此格式数据的另一个应用程序时,修改属性文件才有意义。
示例2:Java程序将新的键值对写入属性文件
因此,如果您遇到类似的情况,那么在PropertiesCache.java中创建两个类似的方法:
public void setProperty(String key, String value){ configProp.setProperty(key, value); } public void flush() throws FileNotFoundException, IOException { try (final OutputStream outputstream = new FileOutputStream("application.properties");) { configProp.store(outputstream,"File Updated"); outputstream.close(); } }
- 使用setProperty(k, v)方法将新属性写入属性文件。
- 使用flush()方法将更新的属性写回到application.properties文件中。
PropertiesCache cache = PropertiesCache.getInstance(); if(cache.containsKey("country") == false){ cache.setProperty("country", "CHINA"); } //验证 property System.out.println(cache.getProperty("country")); //写入文件 PropertiesCache.getInstance().flush();
输出:
Reading all properties from the file CHINA
更新后的属性文件如下:
#File Updated #Fri Aug 14 16:14:33 IST 2020 firstName=Lokesh lastName=Gupta technology=java blog=panizye.com
country=CHINA
以上是使用Java读取和写入属性文件的简单易用的教程。