示例配置文件
app.config:
app.name=MyApp
app.version=1.0
使用读取配置示例代码:
package org.wonhero.example.util;import java.io.*;import java.net.URL;import java.util.Objects;import java.util.Properties;public class PropertiesExample { public static void main(String[] args) { Properties prop = new Properties(); try { // 配置文件名 String fileName = "app.config"; ClassLoader classLoader = PropertiesExample.class.getClassLoader(); // 确保配置文件存在 URL res = Objects.requireNonNull(classLoader.getResource(fileName), "Can't find configuration file app.config"); InputStream is = new FileInputStream(res.getFile()); // 载入配置文件 prop.load(is); // 获取app.name key的值 System.out.println(prop.getProperty("app.name")); // 获取app.version key的值 System.out.println(prop.getProperty("app.version")); // 获取"app.type"的值,如果不存在,则返回默认值"wonhero" System.out.println(prop.getProperty("app.type","wonhero")); } catch (IOException e) { e.printStackTrace(); } }}
输出结果:
MyApp
1.0
wonhero