Properties类的使用总结  

   建议代码, 资源文件只要放在classpath下面即可: 

 
  
  1. Properties prop = new Properties(); 
  2.             InputStream inStream = DaoFactory.class.getClassLoader() 
  3.                     .getResourceAsStream("daoconfig.properties"); 
  4.             prop.load(inStream); 
  5.             String userDaoClass = prop.getProperty("userDaoClass"); 
  6.             Class clazz = Class.forName(userDaoClass); 
  7.             userDao = (UserDao) clazz.newInstance(); 

 通过Properties方式读取xml文件:product.xml

 
  
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> 
  3. <properties> 
  4.     <comment>Hello </comment> 
  5.     <entry key="1">bar </entry> 
  6.     <entry key="2">baz </entry> 
  7. </properties>  

java程序:PropertyDemo.java

 
  
  1. public class PropertyDemo { 
  2.     public static void main(String[] args) { 
  3.         Properties pro = new Properties(); 
  4.         try { 
  5.             pro.loadFromXML(PropertyDemo.class.getClassLoader().getResourceAsStream("product.xml")); 
  6.             System.out.println(pro.get("1")); 
  7.         } catch (IOException e) { 
  8.             e.printStackTrace(); 
  9.         } 
  10.     } 

推荐方式: InputStream in = Object.class.getResourceAsStream("/test.properties"); 读取classpath下的test.properties,一定要加上"/"

读取classpath(即src/main/resources)下面的文件方式: 

 
  
  1. String filePath = System.getProperty("user.dir") + File.separator 
  2.                     + "1.txt"
  3.             // ① 使用系统文件路径方式加载文件 
  4.             Resource res1 = new FileSystemResource(filePath); 
  5.  
  6.             // ② 使用类路径方式加载文件 
  7.             Resource res2 = new ClassPathResource("conf/file1.txt"); 
  8.             InputStream ins1 = res1.getInputStream(); 
  9.             InputStream ins2 = res2.getInputStream(); 

【注意】使用的spring的帮助类,需要加入依赖:

 
  
  1. <dependency> 
  2.         <groupId>com.alibaba.external</groupId> 
  3.         <artifactId>sourceforge.spring.core</artifactId> 
  4.         <version>2.0.7</version> 
  5.     </dependency> 

 

 

在Java中,Properties类用于读取properties类型的配置文件的。默认情况下,读取的配置文件位置是在工程的classpath路径下面,即properties文件必须写在整个工程的根目录下面, 而不是src下面。(System.out.println(new File("myconfig.properties").getAbsoluteFile());执行结果:'D:\workspace_sum\pc2\demo\myconfig.properties', 其中D:\workspace_sum\pc2\demo为工程目录)

【注意】获取文件或文件夹的绝对地址:getCanonicalPath或者getCanonicalFile

 
  
  1. File file = new File("pom.xml"); 
  2.       System.out.println(file.getCanonicalPath()); 
  3.       System.out.println(file.getCanonicalFile()); 

执行结果:

 
  
  1. D:\codes\sourcecodes\victoria\trunk\victoria.maven.jmeter\pom.xml 
  2. D:\codes\sourcecodes\victoria\trunk\victoria.maven.jmeter\pom.xml 

 

URL base = this.getClass().getResource(""); //先获得本类的所在位置,
this.getClass().getClassLoader().getResource(""); //获取classpath的路径

 


  Java读取配置文件 myconfig.properties的样例代码如下:
Properties pro = new Properties();
    pro.load( new FileInputStream( new File( "myconfig.properties")));
    String name = pro.getProperty( "name");
    System.out.println(name);

或者通过当前对象的class loader来装在该配置文件

InputStream in = Demo.class.getResourceAsStream("/myconfig.properties"); 

InputStream in = Demo.class.getClassLoader().getResourceAsStream("/myconfig.properties"); 

获取所有的键:
@SuppressWarnings( "unchecked")
   public List<String> getPc2Service() {
    List<String> list = new ArrayList<String>();
     try {
      pros.load( new FileInputStream( new File(
           "src/main/resources/percent.properties")));
      Enumeration<String> enumeration = (Enumeration<String>) pros
          .propertyNames();
       while (enumeration.hasMoreElements()) {
        list.add(enumeration.nextElement());
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
     return list;
  }
 

2、获取所有的行

servers.txt位于src/main/resources路径下面, ‘ /servers.txt ’为绝对路径, 表示 servers.txt文件
在CLASSPATH路径下面 ; ‘ servers.txt ’表示 和要读取java类在同一目录下面
 
    
  1. public List<String> getAllServerIps() throws Exception { 
  2.         List<String> list = new ArrayList<String>(); 
  3.  
  4.         BufferedReader bufferReader = new BufferedReader(new InputStreamReader( 
  5.                 this.getClass().getResourceAsStream( 
  6.                         "/servers.txt"))); 
  7.         String buf = null
  8.         while ((buf = bufferReader.readLine()) != null) { 
  9.             list.add(buf); 
  10.         } 
  11.         return list; 
  12.     } 
 
 
 
下面是网友的分析:
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章  原始出处 、作者信息和本声明。否则将追究法律责任。 http://lavasoft.blog.51cto.com/62575/62174
Java读取properties文件的思考
 
Java读取properties文件的方法比较多,网上我最多的文章是“Java读取properties文件的六种方法”,但在Java应用中,最常用还是通过java.lang.Class类的getResourceAsStream(String name) 方法来实现,但我见到众多读取properties文件的代码中,都会这么干:
 
InputStream in = getClass().getResourceAsStream("资源Name");
 
这里面有个问题,就是getClass()调用的时候默认省略了this!我们都知道,this是不能在static(静态)方法或者static块中使用的,原因是static类型的方法或者代码块是属于类本身的,不属于某个对象,而this本身就代表当前对象,而静态方法或者块调用的时候是不用初始化对象的。
 
问题是:假如我不想让某个类有对象,那么我会将此类的默认构造方法设为私有,当然也不会写别的共有的构造方法。并且我这个类是工具类,都是静态的方法和变量,我要在静态块或者静态方法中获取properties文件,这个方法就行不通了。
 
那怎么办呢?其实这个类就不是这么用的,他仅仅是需要获取一个Class对象就可以了,那还不容易啊--取所有类的父类Object,用Object.class难道不比你的用你正在写类自身方便安全吗 ?呵呵,下面给出一个例子,以方便交流。
 
import java.util.Properties; 
import java.io.InputStream; 
import java.io.IOException; 

/** 
* 读取Properties文件的例子 
* File: TestProperties.java 
* User: leizhimin 
* Date: 2008-2-15 18:38:40 
*/
 
public  final  class TestProperties { 
     private  static String param1; 
     private  static String param2; 

     static { 
        Properties prop =  new Properties(); 
        InputStream in = Object. class.getResourceAsStream( "/test.properties"); 
         try { 
            prop.load(in); 
            param1 = prop.getProperty( "initYears1").trim(); 
            param2 = prop.getProperty( "initYears2").trim(); 
        }  catch (IOException e) { 
            e.printStackTrace(); 
        } 
    } 

     /** 
     * 私有构造方法,不需要创建对象 
     */
 
     private TestProperties() { 
    } 

     public  static String getParam1() { 
         return param1; 
    } 

     public  static String getParam2() { 
         return param2; 
    } 

     public  static  void main(String args[]){ 
        System.out.println(getParam1()); 
        System.out.println(getParam2()); 
    } 
}
 
运行结果:
151 
152 

Process finished with exit code 0
 
 
当然,把Object.class换成int.class照样行,呵呵,大家可以试试。
 
另外,如果是static方法或块中读取Properties文件,还有一种最保险的方法,就是这个类的本身名字来直接获取Class对象,比如本例中可写成TestProperties.class,这样做是最保险的方法。

 ------------------------------------------------------------------------------------------------

Properties的测试类:PropertiesDemo.java

 
  
  1. public class PropertiesDemo { 
  2.     private static Properties props; 
  3.  
  4.     public static void main(String[] args) { 
  5.         props = new Properties(); 
  6.         // 用props.setProperty("key", "value")设定(key, value)配对 
  7.         props.setProperty("key1""value1"); 
  8.         props.setProperty("key2""中文测试"); 
  9.         // 用 props.list(System.out)在console 印出props中所有的(key, value)配对 
  10.         // -- listing properties -- 
  11.         // key2=中文测试 
  12.         // key1=value1 
  13.         System.out.println("在console 印出props中所有的(key, value)配对"); 
  14.         props.list(System.out); 
  15.         System.out.println(); 
  16.          
  17.         // 设定重覆的(key, value)配对会覆盖掉 
  18.         // -- listing properties -- 
  19.         // key2=中文测试 
  20.         // key1=更改value1 
  21.         System.out.println("印出更改後所有的(key, value)配对"); 
  22.         props.setProperty("key1""更改value1"); 
  23.         props.list(System.out); 
  24.         System.out.println(); 
  25.          
  26.          
  27.         try { 
  28.             // 输出props中所有的(key, value)配对到xml(storeToXML)及txt(store) 
  29.             // 输出後Stream不会自動關閉必須手動關閉,否則有可能出错(不是在()中使用new時) 
  30.             // storeToXML(OutputStream os, Stirng comment, String encode) 
  31.             // storeToXML(OutputStream os, Stirng comment) encode預设使用 UTF-8 
  32.             props.storeToXML(new FileOutputStream("properties.xml"), 
  33.                     "storeToXML"); 
  34.             props.store(new FileOutputStream("properties.properties"), "store"); 
  35.         } catch (FileNotFoundException e) { 
  36.             e.printStackTrace(); 
  37.         } catch (IOException e) { 
  38.             e.printStackTrace(); 
  39.         } 
  40.         props.clear(); 
  41.         try { 
  42.             // props.getProperty(key)读出(key, value)配对 
  43.             // props.getProperty(String key, String defaultWhenNotFound) 
  44.             // props.getProperty(String key) throws exception when not found 
  45.             System.out.println("props.getProperty(key)读出(key, value)配对"); 
  46.             props.load(new FileInputStream("properties.properties")); 
  47.             System.out.println(props.getProperty("key""test")); // default 
  48.                                                                     // value 
  49.                                                                     // test 
  50.             System.out.println(props.getProperty("key1")); 
  51.             props.clear(); 
  52.             System.out.println(); 
  53.         } catch (FileNotFoundException e) { 
  54.             e.printStackTrace(); 
  55.         } catch (IOException e) { 
  56.             e.printStackTrace(); 
  57.         } 
  58.         try { 
  59.             // 印出從 properties.xml 读出的所有(key, value)配对 
  60.             System.out.println("印出properties.xml读出的所有(key, value)配对"); 
  61.             props.loadFromXML(new FileInputStream("properties.xml")); 
  62.             props.setProperty("key3""new value"); 
  63.             props.list(System.out); 
  64.             // 将新配对写回 properties.xml,串流沒出错 
  65.             props.storeToXML(new FileOutputStream("properties.xml"), 
  66.                     "storeToXML"); 
  67.         } catch (FileNotFoundException e) { 
  68.             e.printStackTrace(); 
  69.         } catch (IOException e) { 
  70.             e.printStackTrace(); 
  71.         } 
  72.     }