properties的应用

properties后缀的文件主要 功能为 键 值对,根据键来获取相应的值。

 

以下是个小例子: PropertiesUtils工具类

 

private static Properties docProps = null;

 

static {

  

  //获得properties文件的内容

   if(docProps == null) {

       docProps = new Properties();

       docProps.load(PropertiesUtils.getResourceAsStream(properties文件路径));    

  

  }

 

 

}

 

  //通过路径获得资源

    public static InputStream getResourceAsStream( String resouce )
    {
        ClassLoader cl = PropertiesUtils.class.getClassLoader();
        if( cl!=null )
            return cl.getResourceAsStream( resouce );
        else
            return ClassLoader.getSystemResourceAsStream( resouce );
    }

 

 //通过传递进来的名字组装 键,从properties中获取 对应值

   public static String getWordFileName(String configNum)
   {
       String returnVal = docProps.getProperty( "word." + configNum );
       if( returnVal == null )
            return returnVal;
   }

 

  //调用getResourceAsStream方法 来最终获取到 资源文件的输入流

   public static InputStream getWordFile(String configNum) throws FileNotFoundException
  {
      try
      {
          String fileName = getWordFileName( configNum );
          return getResourceAsStream( Path.WORD + fileName );
      }
      catch (Exception e)
      {          

      }
      return null;
  }

 

 另外,附上两个例子:

 

1.  

"daoconfig.properties"文件 UserDaoClass=com.jdbc.test.dao.impl.UserDaoImpl Java代码 public class DaoFactory { private static UserDao userDao = null; private static DaoFactory instance = new DaoFactory(); private DaoFactory() { try { Properties prop = new Properties(); //InputStream inStream = new FileInputStream(new File("src/daoconfig.properties")); InputStream inStream = DaoFactory.class.getClassLoader() .getResourceAsStream("daoconfig.properties"); prop.load(inStream); String userDaoClass = prop.getProperty("UserDaoClass"); userDao = (UserDao) Class.forName(userDaoClass).newInstance(); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } public static DaoFactory getInstance() { return instance; } public UserDao getUserDao() { return userDao; } }

 

2.

package io; import java.io.InputStream; public class PropertiesUtil { public static void main(String[] args) { String path = "io/a.txt"; InputStream in = getResourceAsStream(path); System.out.println(in); } private static InputStream getResourceAsStream(String path) { InputStream in; ClassLoader c1 = PropertiesUtil.class.getClassLoader(); if(c1 != null) { System.out.println("c1不是空的"); System.out.println(path); in = c1.getResourceAsStream(path); } else { System.out.println("c1是空的"); in = ClassLoader.getSystemResourceAsStream(path); } return in; } }

 

说明:

例子2中的 文档路径要小心,很容易搞错了。

 

1,用Class.getResourceAsStream() 时,路径应该是以"/"开头的,
如:Test.class.getResourceAsStream("/test.bin");
2,如果直接用ClassLoader.getResourceAsStream()不用以"/"开头.
如,ClassLoader.getSystemResourceAsStream(("test.bin");

 

你可能感兴趣的:(exception,properties,String,ClassLoader,null,Path)