Java Properties Load from File load(String resource)

Here you can find the source of load(String resource)

Description

Load properties from the given name resource.

License

Apache License

Parameter

Parameter Description
resource name a of resource.

Return

empty properties if no resource found.

Declaration

public static Map<String, Object> load(String resource) 

Method Source Code

//package com.java2s;
/*//  ww  w.j av a2 s.  c om
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
*/

import java.io.FileInputStream;
import java.io.InputStream;

import java.util.HashMap;

import java.util.Map;
import java.util.Properties;

public class Main {
    /**
     * Load properties from the given name resource.
     * The given named resource is first looked up as resource on the current thread's context
     * and if not found as a file input.
     * 
     * @param resource name a of resource. 
     * 
     * @return empty properties if no resource found.
     */
    public static Map<String, Object> load(String resource) {
        Properties p = new Properties();
        try {
            InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
            if (stream == null) {
                stream = new FileInputStream(resource);
            }
            p.load(stream);
        } catch (Exception e) {
            System.err.println("Error reading " + resource + " due to " + e);
        }
        return toMap(p);
    }

    public static Map<String, Object> toMap(Properties p) {
        Map<String, Object> result = new HashMap<String, Object>();
        for (Object k : p.keySet()) {
            result.put(k.toString(), p.get(k));
        }
        return result;
    }
}

Related

  1. load(String filename)
  2. load(String fileName)
  3. load(String path)
  4. load(String propertiesString)
  5. load(String resource)
  6. load(String[] paths, String fileName)
  7. loadAccessTokenProperties( InputStream inputStream)
  8. loadApiProperties(InputStream inputStream)
  9. loadBuildProperties(File projectRootDir)