目录
深入理解 Java 中的 java.util.Properties 及其打印方式
1. java.util.Properties 简介
2. Properties 的应用场景
3. Properties 的基本使用
3.1 创建并存储 Properties
3.2 读取 Properties 文件
4. Properties 的打印方式
4.1 使用 store 方法输出到 OutputStream
4.2 使用 list 方法打印到 PrintStream
4.3 直接遍历并打印
5. 注意事项
6. 小结
深入理解 Java 中的 java.util.Properties
及其打印方式
1. java.util.Properties
简介
java.util.Properties
是 Java 提供的一个用于管理**键值对(key-value)**的类,主要用于存储配置参数,如数据库连接信息、国际化资源、应用程序设置等。
它继承自 Hashtable<Object, Object>
,但通常只用于存储 String 类型的键值。
2. Properties
的应用场景
Properties
在实际开发中的常见应用场景包括:
- 读取应用配置文件(如
config.properties
) - 管理国际化资源(如
messages.properties
) - 存储数据库连接信息(如
jdbc.properties
) - 动态调整系统参数(如
log4j.properties
) - 存储 JVM 运行时环境参数(如
System.getProperties()
)
3. Properties
的基本使用
3.1 创建并存储 Properties
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;public class PropertiesExample {public static void main(String[] args) throws IOException {Properties properties = new Properties();properties.setProperty("username", "admin");properties.setProperty("password", "123456");properties.setProperty("url", "jdbc:mysql://localhost:3306/testdb");// 保存到文件try (FileOutputStream out = new FileOutputStream("config.properties")) {properties.store(out, "Database Configuration");}}
}
3.2 读取 Properties
文件
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;public class ReadProperties {public static void main(String[] args) throws IOException {Properties properties = new Properties();try (FileInputStream in = new FileInputStream("config.properties")) {properties.load(in);}System.out.println("Username: " + properties.getProperty("username"));System.out.println("Password: " + properties.getProperty("password"));System.out.println("URL: " + properties.getProperty("url"));}
}
4. Properties
的打印方式
4.1 使用 store
方法输出到 OutputStream
store(OutputStream out, String comments)
方法可以将 Properties
内容格式化后输出到控制台或文件。
Properties properties = new Properties();
properties.setProperty("key1", "value1");
properties.setProperty("key2", "value2");properties.store(System.out, "Properties Output");
4.2 使用 list
方法打印到 PrintStream
list(PrintStream out)
可以直接输出 Properties
的内容,格式化方式类似 store
方法。
properties.list(System.out);
4.3 直接遍历并打印
for (String key : properties.stringPropertyNames()) {System.out.println(key + "=" + properties.getProperty(key));
}
5. 注意事项
store
和list
方法输出时,非 ASCII 字符会被转换成 Unicode 形式(如你好
)。如果需要保留中文等字符,建议使用PrintWriter
。Properties
继承自Hashtable
,线程安全,但在高并发情况下仍需额外同步控制。Properties
默认不支持有序存储,如果需要按顺序存储,可使用LinkedHashMap
替代。- 键值均为
String
,如果存储其他对象,需要进行额外的序列化处理。
6. 小结
java.util.Properties
是 Java 中常用的配置存储工具,广泛应用于各种参数配置场景。- 它继承自
Hashtable
,但主要用于存储字符串键值对。 - 通过
store
、list
和遍历等方式可以打印Properties
内容。 - 在使用
Properties
时,需要注意线程安全、字符编码以及存储顺序等问题。
在日常开发中,合理使用 Properties
可以提高代码的可维护性和灵活性,使配置管理更加高效和方便!