|
當(dāng)前位置:我的異常網(wǎng)? Java相關(guān) ? 怎么讀取war包中的properties文件,不使用web請(qǐng)求上 怎么讀取war包中的properties文件,不使用web請(qǐng)求上下文的方式實(shí)現(xiàn)www.MyException.Cn 網(wǎng)友分享于:2013-02-24 瀏覽:342次 如何讀取war包中的properties文件,不使用web請(qǐng)求上下文的方式實(shí)現(xiàn) 如何讀取war包中的properties文件,不使用web請(qǐng)求上下文的方式實(shí)現(xiàn), 項(xiàng)目需求,我想在java project項(xiàng)目中,寫(xiě)個(gè)類(lèi)可以讀取war包中的配置文件信息 有什么好的辦法呀? 請(qǐng)高手解惑,不勝感激!?。?br> ------解決方案--------------------
執(zhí)行前需要將sms.properties文件放在src目錄。。
package com.test.impt;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
public class ReadProperties {
// 配置文件名稱(chēng)
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 {
// 配置文件名稱(chēng)
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;
}
}發(fā)布此文章僅為傳遞網(wǎng)友分享,不代表本站觀點(diǎn),若侵權(quán)請(qǐng)聯(lián)系我們刪除,本站將不對(duì)此承擔(dān)任何責(zé)任。
|
|
|