load Properties from resource - Java java.util

Java examples for java.util:Properties File

Description

load Properties from resource

Demo Code


//package com.java2s;

import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.InputStream;

import java.io.PrintWriter;
import java.io.StringWriter;

import java.util.Properties;

public class Main {
    public static void main(String[] argv) throws Exception {
        String pProp = "java2s.com";
        System.out.println(loadProperties(pProp));
    }//from w w  w .  ja va  2s  .  c om

    public static Properties loadProperties(String pProp) {
        if (pProp == null) {
            pProp = "conf.properties";
        }
        Properties lProp = new Properties();
        ClassLoader lClassLoader = Thread.currentThread()
                .getContextClassLoader();
        try {
            InputStream lResourceAsStream = lClassLoader
                    .getResourceAsStream("conf.properties");
            if (lResourceAsStream != null) {
                lProp.load(lResourceAsStream);
            }
        } catch (FileNotFoundException e) {
            logError("Warning, expected properties file:", pProp);
        } catch (IOException e) {
            logError("IOException :", lProp, e);
        }
        return lProp;
    }

    public static void logError(Object... pObjects) {
        System.err.println(getMsg(pObjects));
    }

    private static StringBuilder getMsg(Object... pObjects) {
        StringBuilder lMsg = new StringBuilder();
        for (Object o : pObjects) {
            if (o != null) {
                if (o instanceof Throwable) {
                    Throwable e = (Throwable) o;
                    StringWriter lStack = new StringWriter();
                    e.printStackTrace(new PrintWriter(lStack));
                    lMsg.append(e.getClass().getSimpleName());
                    lMsg.append(":");
                    lMsg.append(e.getMessage());
                    lMsg.append('\n');
                    lMsg.append(lStack);
                }
                lMsg.append(o);
                lMsg.append(' ');
            }
        }
        return lMsg;
    }
}

Related Tutorials