How do I load file from resource directory?

In the following code snippet we will learn how to load files from resource directory. Resource files can be in a form of image, audio, text, etc. Text resource file for example can be used to store application configurations, such as database configuration.

To load this resource file you can use a couple methods utilizing the java.lang.Class methods or the java.lang.ClassLoader methods. Both Class and ClassLoader provides getResource() and getResourceAsStream() methods to load resource file. The first method return a URL object while the second method return an InputStream.

When using the Class method, if the resource name started with “/” that identifies it is an absolute name. Absolute name means that it will load from the specified directory name or package name. While if it is not started with “/” then it is identified as a relative name. This means that it will look in the same package as the class that tries to load the resource.

App.class.getResource("database.conf");

The snippet will attempt to load the resource file from the same package as the App class. If the App class package is org.kodejava then the database.conf file must be located at /org/kodejava/. This is the relative resource name.

App.class.getResource("/org/kodejava/conf/database.conf"):

The snippet will attempt to load the resource file from the given package name. You should place the configuration file under /org/kodejava/conf/ to enable the application to load it. This is the absolute resource name.

Below is a snippet that use the Class method to load resources.

private void loadUsingClassMethod() throws IOException {
    System.out.println("LoadResourceFile.loadUsingClassMethod");
    Properties properties = new Properties();

    // Load resource relatively to the LoadResourceFile package.
    // This actually load resource from
    // "/org/kodejava/lang/database.conf".
    URL resource = getClass().getResource("database.conf");
    properties.load(new FileReader(Objects.requireNonNull(resource).getFile()));
    System.out.println("JDBC Driver: " + properties.get("jdbc.driver"));

    // Load resource using absolute name. This will read resource
    // from the root of the package. This will load "/database.conf".
    InputStream is = getClass().getResourceAsStream("/database.conf");
    properties.load(is);
    System.out.println("JDBC Driver: " + properties.get("jdbc.driver"));
}

When we use the ClassLoader method the resource name should not begins with a “/“. This method will not apply any absolute / relative transformation to the resource name like the Class method. Here a snippet of a method that use the ClassLoader method.

private void loadUsingClassLoaderMethod() throws IOException {
    System.out.println("LoadResourceFile.loadUsingClassLoaderMethod");
    Properties properties = new Properties();

    // When using the ClassLoader method, the resource name should
    // not be started with "/". This method will not apply any
    // absolute/relative transformation to the resource name.
    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource("database.conf");
    properties.load(new FileReader(Objects.requireNonNull(resource).getFile()));
    System.out.println("JDBC URL: " + properties.get("jdbc.url"));

    InputStream is = classLoader.getResourceAsStream("database.conf");
    properties.load(is);
    System.out.println("JDBC URL: " + properties.get("jdbc.url"));
}

Below is the main program that calls the methods above.

package org.kodejava.lang;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;

public class LoadResourceFile {
    public static void main(String[] args) throws Exception {
        LoadResourceFile demo = new LoadResourceFile();
        demo.loadUsingClassMethod();
        demo.loadUsingClassLoaderMethod();
    }
}

In the snippet above we load two difference resources. One contains Oracle database configuration and the other is MySQL database configuration.

/resources/org/kodejava/lang/database.conf

jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.username=kodejava
jdbc.password=kodejava123

/resources/database.conf

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/kodejava
jdbc.username=kodejava
jdbc.password=kodejava123

The result of this code snippet are:

LoadResourceFile.loadUsingClassMethod
JDBC Driver: oracle.jdbc.driver.OracleDriver
JDBC Driver: com.mysql.jdbc.Driver

LoadResourceFile.loadUsingClassLoaderMethod
JDBC URL: jdbc:mysql://localhost/kodejava
JDBC URL: jdbc:mysql://localhost/kodejava

How do I get the component type of array?

The Class.getComponentType() method call returns the Class representing the component type of array. If this class does not represent an array class this method returns null reference instead.

package org.kodejava.lang.reflect;

public class ComponentTypeDemo {
    public static void main(String[] args) {
        String[] words = {"and", "the"};
        int[][] matrix = {{1, 1}, {2, 1}};
        Double number = 10.0;

        Class<?> clazz = words.getClass();
        Class<?> cls = matrix.getClass();
        Class<?> clz = number.getClass();

        // Gets the type of array component.
        Class<?> type = clazz.getComponentType();
        System.out.println("Words type: " +
                type.getCanonicalName());

        // Gets the type of array component.
        Class<?> matrixType = cls.getComponentType();
        System.out.println("Matrix type: " +
                matrixType.getCanonicalName());

        // It will return null if the class doesn't represent
        // an array.
        Class<?> numberType = clz.getComponentType();
        if (numberType != null) {
            System.out.println("Number type: " +
                    numberType.getCanonicalName());
        } else {
            System.out.println(number.getClass().getName() +
                    " class is not an array");
        }
    }
}

This program print the following output:

Words type: java.lang.String
Matrix type: int[]
java.lang.Double class is not an array

How do I determine if a class object represents an array class?

For checking if a class object is representing an array class we can use the isArray() method call of the Class object. This method returns true if the checked object represents an array class and false otherwise.

package org.kodejava.lang.reflect;

public class IsArrayDemo {
    public static void main(String[] args) {
        int[][] matrix = {{1, 1}, {2, 1}};
        Class<?> clazz = matrix.getClass();

        // Check if the class object represents an array class
        if (clazz.isArray()) {
            System.out.println(clazz.getSimpleName() +
                    " is an array class.");
        } else {
            System.out.println(clazz.getSimpleName() +
                    " is not an array class.");
        }
    }
}

How do I get direct superclass and interfaces of a class?

Java reflection also dealing with inheritance concepts. You can get the direct interfaces and direct super class of a class by using method getInterfaces() and getSuperclass() of java.lang.Class object.

  • getInterfaces() will returns an array of Class objects that represent the direct super interfaces of the target Class object.
  • getSuperclass() will returns the Class object representing the direct super class of the target Class object or null if the target represents Object class, an interface, a primitive type, or void.
package org.kodejava.lang.reflect;

import javax.swing.*;
import java.util.Date;

public class GetSuperClassDemo {
    public static void main(String[] args) {
        GetSuperClassDemo.get(String.class);
        GetSuperClassDemo.get(Date.class);
        GetSuperClassDemo.get(JButton.class);
        GetSuperClassDemo.get(Timer.class);
    }

    public static void get(Class<?> clazz) {
        // Gets array of direct interface of clazz object
        Class<?>[] interfaces = clazz.getInterfaces();

        System.out.format("Direct Interfaces of %s:%n",
                clazz.getName());
        for (Class<?> clz : interfaces) {
            System.out.println(clz.getName());
        }

        // Gets direct superclass of clazz object
        Class<?> superclz = clazz.getSuperclass();
        System.out.format("Direct Superclass of %s: is %s %n",
                clazz.getName(), superclz.getName());
        System.out.println("====================================");
    }
}

Here is the result of the code snippet:

Direct Interfaces of java.lang.String:
java.io.Serializable
java.lang.Comparable
java.lang.CharSequence
Direct Superclass of java.lang.String: is java.lang.Object 
====================================
Direct Interfaces of java.util.Date:
java.io.Serializable
java.lang.Cloneable
java.lang.Comparable
Direct Superclass of java.util.Date: is java.lang.Object 
====================================
Direct Interfaces of javax.swing.JButton:
javax.accessibility.Accessible
Direct Superclass of javax.swing.JButton: is javax.swing.AbstractButton 
====================================
Direct Interfaces of javax.swing.Timer:
java.io.Serializable
Direct Superclass of javax.swing.Timer: is java.lang.Object 
====================================

How do I check if a class represent an interface type?

You can use the isInterface() method call of the java.lang.Class to identify if a class objects represent an interface type.

package org.kodejava.lang.reflect;

import java.io.Serializable;

public class IsInterfaceDemo {
    public static void main(String[] args) {
        IsInterfaceDemo.get(Serializable.class);
        IsInterfaceDemo.get(Long.class);
    }

    private static void get(Class<?> clazz) {
        if (clazz.isInterface()) {
            System.out.println(clazz.getName() +
                    " is an interface type.");
        } else {
            System.out.println(clazz.getName() +
                    " is not an interface type.");
        }
    }
}

Here is the result of the program:

java.io.Serializable is an interface type.
java.lang.Long is not an interface type.