您的位置:首页 > 其它

加载src目录下的文件的几种方式

2013-12-12 17:30 323 查看
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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  测试