`
mjj192837
  • 浏览: 24594 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java读取Properties文件的六种方法 转载

阅读更多

使用J2SE API读取Properties文件的六种方法:

1.使用java.util.Properties类的load()方法

示例: InputStream in = new 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);

 

(

Class.getResourceAsStream和ClassLoader.getResourceAsStream的区别
两个都可以用于从 classpath 里面进行资源读取,  classpath包含classpath中的路径
和classpath中的jar。

两个方法的区别是资源的定义不同, 一个主要用于相对与一个object取资源,而另一个用于取相对于classpath的
资源,用的是绝对路径。

在使用Class.getResourceAsStream 时, 资源路径有两种方式, 一种以 / 开头,则这样的路径是指定绝对
路径, 如果不以 / 开头, 则路径是相对与这个class所在的包的。

在使用ClassLoader.getResourceAsStream时, 路径直接使用相对于classpath的绝对路径。

举例,下面的三个语句,实际结果是一样的:
com.explorers.Test.class.getResourceAsStream("abc.jpg")
com.explorers.Test.class.getResourceAsStream("/com/explorers/abc.jpg")
ClassLoader.getResourceAsStream("com/explorers/abc.jpg")

 

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

 

)

 

补充

Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法

示例:InputStream in = context.getResourceAsStream(path);

Properties p = new Properties();

p.load(in);

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics