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

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

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;
    }

Add a jar file to Java load path at run time

Sometimes it is necessary to amend the class load path at run time. For example, dynamically adding jar files containing user-configurable JDBC data sources. The way this is done is truly monstrous -- the URL Path format was only revealed when a colleague looked into the Java library sources.

import java.net.URL;
import java.io.IOException;
import java.net.URLClassLoader;
import java.net.MalformedURLException;

public class JarFileLoader extends URLClassLoader
{
    public JarFileLoader (URL[] urls)
    {
        super (urls);
    }

    public void addFile (String path) throws MalformedURLException
    {
        String urlPath = "jar:file://" + path + "!/";
        addURL (new URL (urlPath));
    }

    public static void main (String args [])
    {
        try
        {
            System.out.println ("First attempt...");
            Class.forName ("org.gjt.mm.mysql.Driver");
        }
        catch (Exception ex)
        {
            System.out.println ("Failed.");
        }

        try
        {
            URL urls [] = {};

            JarFileLoader cl = new JarFileLoader (urls);
            cl.addFile ("/opt/mysql-connector-java-5.0.4/mysql-connector-java-5.0.4-bin.jar");
            System.out.println ("Second attempt...");
            cl.loadClass ("org.gjt.mm.mysql.Driver");
            System.out.println ("Success!");
        }
        catch (Exception ex)
        {
            System.out.println ("Failed.");
            ex.printStackTrace ();
        }
    }
}
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS