A simple example to show how to use java properties file

I am trying to make a simplified Database class for Database connection and query operation.  It’s a good idea to put the database config information to a properties file. In this way, when the code is packaged to a jar file, other users can just put the different database configuration file in the config.properties file. This is also useful when edit your code in several different locations. When the code is updated at school/work, you can update the .java file only. After that, when you work at home, you then can download that .java code file only and work/update it. Sometimes, this works as well as SVN if you don’t have one.

Steps:

1. create the file hierarchy like the following. Mainly remember to put the config.properties file under src package. Other testing code and database class are put in different package under src.

package_explorer

2. The following is the code.

package Test;
 
import java.io.IOException;
import java.util.Properties;
 
public class Test {
 
	public static void main(String[] args) {
		Properties configFile = new Properties();
		try {
			configFile.load(Test.class.getClassLoader().getResourceAsStream("config.properties"));
			String name = configFile.getProperty("name");
			System.out.println(name);
		} catch (IOException e) {
 
			e.printStackTrace();
		}
	}
 
}

Related Articles:

Category: Real Methods  
  • seonuke

    Νice answer back іn return of this queгy wіth геal aгguments аnd exρlaining all
    about that.

  • JP @ garbage collection java

    nice tips. I also like you article on java garbage collection , excellent blog mate. keep it up.