1、獻上工具類
package com.test.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.Properties; public class ConfigUtil { /** * 獲得值 * * @param key 鍵 * @return 值 */ public static String getConfig(String key) { Properties p; p = new Properties(); FileInputStream fis = null; URL url; url = ConfigUtil.class.getClassLoader().getResource("config.properties"); try { fis = new FileInputStream(url.getPath()); p.load(fis); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } return p.getProperty(key); } }
2、創建名字叫config.properties的xml配置文件
文件中的數據以key=value形式書寫,例如:
KEY=123
CODE=890001
3、開始調用
String value= ConfigUtil.getConfig("KEY");
這樣,將會把配置文件中的KEY值123獲取出來,記住,key值不能重復。