java加载配置文件,并读取配置参数

    xiaoxiao2022-07-04  143

    import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.net.URL; import java.util.Properties; public class Configuration { private static Properties properties = new Properties(); static{ try{ /*方法一:通过配置文件的绝对路径 String confPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "config.properties"; BufferedReader bufferedReader = new BufferedReader(new FileReader(confPath)); properties.load(bufferedReader); */ /*方法二:通过搜索类路径,比如/xxx/xxx/config/config.properties,则启动程序时通过-cp指定类路径,即java -cp /xxx/xxx/config */ ClassLoader classLoader = Configuration.class.getClassLoader(); URL url = classLoader.getResource("config.properties"); BufferedReader bufferedReader = new BufferedReader(new FileReader(url.getPath())); properties.load(bufferedReader); }catch(Exception e){ e.printStackTrace(); } } public static String getProperty(String key){ return properties.getProperty(key); } public static String getProperty(String key, String defaultValue){ return properties.getProperty(key,defaultValue); } }

     

    最新回复(0)