className.class.getResourceAsStream :
一: 要加载的文件和.class文件在同一目录下,例如:com.x.y 下有类Test.class ,同时有资源文件config.properties
那么,应该有如下代码:
//前面没有“/”代表当前类的目录
InputStream is1 = Test.class.getResourceAsStream("config.properties");
System.out.println(is1);// 不为null
第二:在Test.class目录的子目录下,例如:com.x.y 下有类Test.class ,同时在 com.x.y.prop目录下有资源文件config.properties
那么,应该有如下代码:
//前面没有“/”代表当前类的目录
InputStream is2 = Test.class.getResourceAsStream("prop/config.properties");
System.out.println(is2);//不为null
第三:不在同目录下,也不在子目录下,例如:com.x.y 下有类Test.class ,同时在 com.m.n 目录下有资源文件config.properties
那么,应该有如下代码:
//前面有“/”,代表了工程的根目录
InputStream is3 = Test.class.getResourceAsStream("/com/m/n/config.properties");
System.out.println(is3);//不为null
ClassLoader.getSystemResourceAsStream :
和className.class.getResourceAsStream 的第三种取得的路径一样,但少了“/”
InputStream is4 = ClassLoader.getSystemResourceAsStream("properties/PayManagment_Config.properties");
System.out.println(is4);//不为null
java解析properties文件的几种方法及用法
1、使用java.util.Properties类的load()方法
示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);
2、使用java.util.ResourceBundle类的getBundle()方法
示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
3、使用java.util.PropertyResourceBundle类的构造函数
示例: InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);
4、使用class变量的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
5、使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
6、使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
示例: InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);
补充
Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);