Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Jean-Pierre Schnyder http://philosophieavivre.blogspot.com/

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

Printing out a Map in sorted order

// print out a Map in sorted order of its keys

    public static String dumpToString(Map<String, Object> map) {
        if (map == null) {
            return Constants.EMPTY_STRING;
        }

        StringBuffer strbuf = new StringBuffer();

        SortedMap<String, Object> sMap = new TreeMap<String, Object>(map);
        Set<Map.Entry<String, Object>> s = sMap.entrySet();

        for (Map.Entry<String, Object> elem : s) {
            String key = elem.getKey();
            Object value = elem.getValue();
            strbuf.append(key);
            strbuf.append("=");
            strbuf.append(value == null ? Constants.EMPTY_STRING : value);
            strbuf.append("\r\n");
        }

        return strbuf.toString();
    }

Recursively dump imbricated Map of Maps

// description of your code here

    public void dumpMapOfMap(Map map) {
        Set s = map.entrySet();
        Iterator sit = s.iterator();
        boolean isFirst = true;

        while (sit.hasNext()) {
            Map.Entry elem = (Map.Entry)sit.next();
            String key = (String)elem.getKey();
            Object value = elem.getValue();

            if (value instanceof String) {
                // recursivity stop condition
                System.out.print(key);
                System.out.print(" : ");
                System.out.println(value);
            } else {
                if (!isFirst) {
                    System.out.println("");
                } else {
                    isFirst = false;
                }
                System.out.println(key);
                Map valueMap = (Map)elem.getValue();
                dumpMapOfMap(valueMap);
            }
        }
    }

Obtaining the value of a public static field by reflexion

// Obtaining the value of a static public constant of a class, here Boolean for example
        Object returnedObj = null;
        try {
            Class clazz = Class.forName("java.lang.Boolean");
            returnedObj = clazz.getField("TRUE").get(clazz);
            assert java.lang.Boolean.TRUE == returnedObj : "wrong returned object";
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return returnedObj;

Printing out the full path of a resource on the classpath

// displaying the full path of a resource found by the class loader on the classpath, here the log4j.xml file
String resourceName = "/log4j.xml"; // pay attention to the leading '/' !
URL location = AnyClass.class.getResource(resourceName);

if (location != null) {
    System.out.println(location.getPath());
} else {
    System.out.println(resourceName + " not found on the classpath");
}

Loading a text file into a String from the classpath

Locate a text file in the classpath and read it into a String

    /** 
     * @param filePath      name of file to open. The file can reside
     *                      anywhere in the classpath
     */
    private String readFileAsString(String filePath) throws java.io.IOException {
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new InputStreamReader(this
            .getClass().getClassLoader().getResourceAsStream(filePath)));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
        return fileData.toString();
    }

Loading a property file from the classpath

Loads a property file located anywhere in the classpath

    private Properties getPropertiesFromClasspath(String propFileName) throws IOException {
        // loading xmlProfileGen.properties from the classpath
        Properties props = new Properties();
        InputStream inputStream = this.getClass().getClassLoader()
            .getResourceAsStream(propFileName);

        if (inputStream == null) {
            throw new FileNotFoundException("property file '" + propFileName
                + "' not found in the classpath");
        }

        props.load(inputStream);

        return props;
    }
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS