日期:2014-05-20 浏览次数:20897 次
执行前需要将sms.properties文件放在src目录。。 package com.test.impt; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; public class ReadProperties { // 配置文件名称 private static final String CONFIG_PROPERTIES_FILE = "sms.properties"; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String filePath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); try { Properties props = loadProperties(filePath + CONFIG_PROPERTIES_FILE); System.out.println(props.getProperty("dx.server.host")); // 成功输出 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Properties loadProperties(String propertiesFile) throws Exception { Properties props = null; // propertiesFile = getPropertiesFile(propertiesFile); // ---------------------------- // ...and if so, then load the values from that external file InputStream in = null; try { in = new FileInputStream(propertiesFile); props = new Properties(); props.load(in); } catch (Exception e) { props = null; } finally { if (in != null) in.close(); } return props; } }
------解决方案--------------------
还有一种方法。。代码量更少的。。 package com.test.impt; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; public class ReadProperties { // 配置文件名称 private static final String CONFIG_PROPERTIES_FILE = "sms.properties"; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub InputStream is = ClassLoader.getSystemResourceAsStream(CONFIG_PROPERTIES_FILE); try { Properties props = loadPropertiesFileStream(is); System.out.println(props.getProperty("dx.server.host")); // 成功输出 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Properties loadPropertiesFileStream(InputStream is) throws Exception { Properties props = null; try { props = new Properties(); props.load(is); } catch (Exception e) { props = null; } finally { if (is != null) is.close(); } return props; } }