java中得到src路徑下文件的經常使用方法

在代碼中通常讀取src下的配置文件java

讀取src路徑下的log4j.properties和message.propertiescode

讀取message.properties文件並將properties中的鍵值對轉爲mapget

PropertiesServlet.class.getClassLoader().getResourceAsStream("/message.properties");返回值是一個InputStreamit

  /**

     * 根據java標準properties文件讀取信息,並賦值爲一個 HashMap<String,String>

     * @param path

     * @param map

     * @return

     * @throws Exception

     */

    public final  Map<String,String> fileToMap(Map<String,String> map) throws Exception{

        if(map == null){

            map = new HashMap<String,String>();

        }

        InputStream isr = null;

        Reader r = null;

        try {

         isr = PropertiesServlet.class.getClassLoader().getResourceAsStream("/message.properties");

            r = new InputStreamReader(isr, "UTF-8");

            Properties props = new Properties();//使用..Properties                 
            props.load(r);
            Set<Entry<Object, Object>> entrySet = props.entrySet();

            for (Entry<Object, Object> entry : entrySet) {

                if (!entry.getKey().toString().startsWith("#")) {

                 

                    map.put(((String) entry.getKey()).trim(), ((String) entry

                            .getValue()).trim());

                }

            }

            return map;

        } finally {

            if (r != null) {

                try {

                    r.close();

                } catch (IOException e) {

                 HLogger.error(e);

                }

            }

            if (isr != null) {

                try {

                    isr.close();

                } catch (Exception e2) {

                 HLogger.error(e2);

                }

            }

        }

    }

LogInit.class.getClassLoader().getResource("//").getPath();返回的是一個String類型的路徑io

 public void init() throws ServletException {

  // TODO Auto-generated method stub

  super.init();

  PropertyConfigurator.configure(LogInit.class.getClassLoader().getResource("//").getPath()+"//log4j-hrp.properties");

 }
相關文章
相關標籤/搜索