Two Methods for loading resource files in Java

Source: Internet
Author: User

Processing configuration files is no longer common for Java Programmers. Servlet, Spring, or Structs all need to deal with configuration files. Java treats the configuration file as a resource and provides two classes to read these resources. One is the Class and the other is the ClassLoader Class.

 

When our own program needs to process configuration files (such as xml files or properties files), we usually encounter two problems:

(1) Where should I put my configuration file?

(2) Why can't I find my configuration file?

 

After learning about the Java resource file loading mechanism, the above two problems are solved.

For the first question, the answer is: Put your resource file in classpath. If the resource file is in jar, add the jar file to classpath.

For the second question, you must check which Class (Class or ClassLoader) You are using to load the resource file, so next we will discuss the loading mechanisms of resource files for the Class and ClassLoader Class respectively.

 

(1) Use the Class to load resource files

Call the getResourceAsStream method of the Class to load the resource file:

Public InputStream getResourceAsStream (String pathToConfigFile );

 

This method receives a String-type parameter (pathToConfigFile) to indicate the address of the resource file. If the load is successful, the input stream (InputStream) of the resource file is returned. If the load fails, null is returned. It is important that there are two methods when passing in the pathToConfigFile parameter. The first method is absolute positioning, that is, pathToConfigFile starts with "/". In this case, Java uses classpath as the root directory, add pathToConfigFile to search for resource files. The second method is relative positioning, that is, pathToConfigFile does not start with "/". the full path of the resource file should be: package path of the class that calls the getResourceAsStream method plus pathToConfigFile. (Change "." to "/" when converting a package into a directory "/")

For example, create a java project in IntelliJ Idea. The directory structure is as follows:

 

This project contains two resources folders, one under the davenkin folder and the other directly under the src folder. The first resources folder contains a config. properties file with the following content:

name = ConfigUnderDavenkin

 

The second resources folder also contains a config. properties file with the following content:

name = ConfigUnderSrc

 

Define ResourceLoader. java in the davenkin package to load the resource file:

package davenkin;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ResourceLoader
{
public static void main(String[] args) throws IOException
{
ResourceLoader resourceLoader = new ResourceLoader();
resourceLoader.loadProperties1();

}

public void loadProperties1() throws IOException
{
InputStream input = null;
try
{
input = Class.forName("davenkin.ResourceLoader").getResourceAsStream("/resources/config.properties");

//also can be this way:
//input = this.getClass().getResourceAsStream("/resources/config.properties");
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
printProperties(input);
}

private void printProperties(InputStream input) throws IOException
{
Properties properties = new Properties();
properties.load(input);
System.out.println(properties.getProperty("name"));
}
}

 

The output result is the content of config. properties in the second resources Folder:

ConfigUnderSrc

 

The reason is (please note ReourceLoader. the red part in the java file): The resource file path (/resources/config. properties. If "/" is removed from the path of the resource file, the relative positioning method is used. In this case, the content of the davenkin/resources/config. properties file should be output.

 

(2) Use the ClassLoader class to load resource files

The ClassLoader Class also provides the same loading method as the Class:

Public InputStream getResourceAsStream (String pathToConfigFile );

 

When you use ClassLoader to load a configuration file, pathToConfigFile cannot start with "/". You can directly search for it under classpath. When searching for resource files, the Class is also a proxy (delegate) for ClassLoader to complete the search function, please refer to the official Java documentation.

 

When using Class and ClassLoader to load resource files, there are several subtle methods. Modify the ResourceLoader. java file as follows:

package davenkin;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ResourceLoader
{
public static void main(String[] args) throws IOException
{
ResourceLoader resourceLoader = new ResourceLoader();
resourceLoader.loadProperties1();
resourceLoader.loadProperties2();
resourceLoader.loadProperties3();
resourceLoader.loadProperties4();
resourceLoader.loadProperties5();
resourceLoader.loadProperties6();
}

public void loadProperties1() throws IOException
{
InputStream input = null;
try
{
input = Class.forName("davenkin.ResourceLoader").getResourceAsStream("/resources/config.properties");
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
printProperties(input);
}

public void loadProperties2() throws IOException
{
InputStream input = null;

input = this.getClass().getResourceAsStream("/resources/config.properties");
printProperties(input);
}

public void loadProperties3() throws IOException
{
InputStream input = this.getClass().getResourceAsStream("resources/config.properties");
printProperties(input);
}

public void loadProperties4() throws IOException
{
InputStream input = this.getClass().getClassLoader().getResourceAsStream("resources/config.properties");
printProperties(input);
}

public void loadProperties5() throws IOException
{
InputStream input = ClassLoader.getSystemResourceAsStream("resources/config.properties");
printProperties(input);
}

public void loadProperties6() throws IOException
{
InputStream input = ClassLoader.getSystemClassLoader().getResourceAsStream("resources/config.properties");

printProperties(input);
}

private void printProperties(InputStream input) throws IOException
{
Properties properties = new Properties();
properties.load(input);
System.out.println(properties.getProperty("name"));
}
}

 

The output result of the above program is (please think about it carefully and be careful (for example, if you add a "/" or add a "/"), the NullPointerException exception will be reported, indicates that your resource file is not found ):

ConfigUnderSrc
ConfigUnderSrc
ConfigUnderDavenkin
ConfigUnderSrc
ConfigUnderSrc
ConfigUnderSrc

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.