转自:http://www.blogjava.net/sxyx2008/
package com.future.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 读取资源配置文件
* @author coder
*
*/
@SuppressWarnings("serial")
public class CommonPropertiesUtil {
@SuppressWarnings("static-access")
public static String getContextPath(){
String contextPath="";
try {
//加载src目录下的文件的几种方式
//注意当使用getClass()方式而不是getClassLoader()时资源文件前的"/"不能省略
//InputStream stream=this.getClass().getResourceAsStream("/common.properties");
//InputStream stream=Thread.currentThread().getClass().getResourceAsStream("/common.properties");
InputStream stream=Thread.currentThread().getContextClassLoader().getResourceAsStream("common.properties");
//谨记这种方式是错误的
//InputStream stream=Thread.currentThread().getClass().getClassLoader().getResourceAsStream("common.properties");
//InputStream stream=Thread.currentThread().getClass().getClassLoader().getSystemResourceAsStream("common.properties");
//InputStream stream=this.getClass().getClassLoader().getSystemResourceAsStream("common.properties");
//InputStream stream=this.getClass().getClassLoader().getResourceAsStream("common.properties");
//InputStream stream=this.getClass().getClassLoader().getSystemResourceAsStream("common.properties");
//InputStream stream=CommonPropertiesUtil.class.getClassLoader().getResourceAsStream("common.properties");
//InputStream stream=CommonPropertiesUtil.class.getClass().getClassLoader().getSystemClassLoader().getResourceAsStream("common.properties");
//InputStream stream=CommonPropertiesUtil.class.getClass().getClassLoader().getSystemClassLoader().getSystemResourceAsStream("common.properties");
Properties properties=new Properties();
properties.load(stream);
contextPath=properties.getProperty("contextPath");
System.out.println(contextPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return contextPath;
}
public static void main(String[] args) {
getContextPath();
}
}
注:当直接使用getClass()而不是getClassLoader()方法时括号中资源文件名称前的/不能省略