[转]Java加载src目录下文件的几种方式
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(); } }
转自http://www.blogjava.net/sxyx2008/
posted on 2012-09-14 11:08 jerry picasso 阅读(228) 评论(0) 收藏 举报
浙公网安备 33010602011771号