7

I am using servlets where I hard-code the database connection details, so if make any change I have to recompile the code. So instead I'd like to use a .properties file (which I can modify later) and use that as the source for my database connection.

The problem is I don't know how to read the property file. Could someone please help me to read the file?

Jasper
  • 2,166
  • 4
  • 30
  • 50
dean
  • 79
  • 1
  • 2
  • 9
  • Even though you already have a lot to read here, I'd like to recommend [this article](http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html?page=1) to you, because it might will help you to get a basic understanding on how to organise your properties. It is fairly old, but the API hasnt changed a lot since then. – crusam Jun 06 '11 at 07:51
  • Related: http://stackoverflow.com/questions/3134581/what-is-the-proper-way-of-handling-configurations-database-login-and-passwords and http://stackoverflow.com/questions/2161054/where-to-place-properties-files-in-a-jsp-servlet-web-application – BalusC Jun 06 '11 at 11:21

13 Answers13

7
   . . .
   // create and load default properties
   Properties defaultProps = new Properties();
   FileInputStream in = new FileInputStream("defaultProperties");
   defaultProps.load(in);
   in.close();

   // create application properties with default
   Properties applicationProps = new Properties(defaultProps);

   // now load properties from last invocation
   in = new FileInputStream("appProperties");
   applicationProps.load(in);
   in.close();
   . . .

Example is coming from here Properties (Java)

The methods of Properties can throw exceptions. - When the file path is not valid (FileNotFoundException). Please try to create a File object and check, whether the File is existing. - ...

Jasper
  • 2,166
  • 4
  • 30
  • 50
Markus Lausberg
  • 12,177
  • 6
  • 40
  • 66
  • But i used Properties method but it throws FileNotFound Exception My code : Properties prop = new Properties(); prop.load(new FileInputStream("file.properties")); – dean Jun 06 '11 at 06:47
  • 2
    you should read the message before you copy&paste your answers everywhere! – Markus Lausberg Jun 06 '11 at 06:49
5

You may take a look at Apache Commons Configuration. Using it you can read properties file like that:

Configuration config = new PropertiesConfiguration("user.properties");
String connectionUrl = config.getString("connection.url");

This information regarding file location may be also important:

If you do not specify an absolute path, the file will be searched automatically in the following locations:

  • in the current directory
  • in the user home directory
  • in the classpath

So in case of reading properties file in a servlet you should put properties file in a classpath (e.g. in WEB-INF/classes).

You can find more examples at their website.

Piotr
  • 5,543
  • 1
  • 31
  • 37
3

The biggest problem in reading a property file in web application is that you actually don't know about the actaul path of the file. So we have to use the relative path and for that we have to use various functions and classes like getresourceAsStream(), InputStream, FileinputStream etc.

And the method getReourceAsStream behaves differently in static and non static methogs.. you can do this in below way

  1. Non Static

    InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties");

  2. Static

    InputStream input = ReadPropertyFile.class.getClassLoader().getResourceAsStream("config.properties");

For complete reference you can follow these links..

http://www.codingeek.com/java/using-getresourceasstream-in-static-method-reading-property-files

http://www.codingeek.com/java/read-and-write-properties-file-in-java-examples/

Hitesh Garg
  • 1,211
  • 1
  • 10
  • 21
3

You can use java.util.Properties

trutheality
  • 23,114
  • 6
  • 54
  • 68
  • 1
    But i used Properties method but it throws FileNotFound Exception My code : Properties prop = new Properties(); prop.load(new FileInputStream("file.properties")); – dean Jun 06 '11 at 06:42
  • 2
    Your properties file needs to be in the classpath. – trutheality Jun 06 '11 at 06:44
2

Below program read the properties file a display using key value pair

                File f1 = new File("abcd.properties");
                FileReader fin = new FileReader(f1);
                Properties pr = new Properties();
                pr.load(fin);
                Set<String> keys = pr.stringPropertyNames();
                Iterator<String> it = keys.iterator();
                String key, value;
                while (it.hasNext())
                    {
                        key = it.next();
                        value = pr.getProperty(key);
                        System.out.println(key+":"+value);
                    }

            }
loknath
  • 1,362
  • 16
  • 25
2

If your application is small enough with only a handful of properties coming from just one or two property files, then I would suggest to use the JDK's own Properties class which load the properties from a file and use it just like the way you use a hashtable. Properties class itself inherits from Hashtable. But, your application is significantly large with sizable number of properties coming from different sources like property files, xml files, system properties then I would suggest to use Apache commons configuration. It presents a unified view of properties from across different configuration sources and allows you to define an override and preference mechanism for common properties appearing in different sources. Refer this article http://wilddiary.com/reading-property-file-java-using-apache-commons-configuration/ for a quick tutorial on using the commons configuration.

Drona
  • 6,886
  • 1
  • 29
  • 35
2

This may work::

Properties prop = new Properties();
FileReader fr = new FileReader(filename);
prop.load(fr);
Set<String> keys = pr.stringPropertyNames();
//now u can get the values from keys.
Aamir
  • 2,380
  • 3
  • 24
  • 54
2
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
Properties p = new Properties();
p.load(in);
in.close();
Marcin Michalski
  • 1,266
  • 13
  • 17
2

The below code, will add a Listener which checks for file configured with dbprops system property. For every given interval it will look if the file is modified, if it is modified it will load the Properties from the file. package com.servlets;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class DBPropsWatcherListener
 implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
ServletContext servletContext = event.getServletContext();
Timer timer = new Timer("ResourceListener");
timer.schedule(new MyWatcherTask(servletContext), 15);
}

public void contextDestroyed(ServletContextEvent event)
{
}

private class MyWatcherTask extends TimerTask
{
private final ServletContext servletContext;
private long lastModifiedTime = -1;


public MyWatcherTask(ServletContext servletContext)
{
    this.servletContext = servletContext;
}

public void run()
{
    try {
        File resourceFile = new File(System.getProperty("dbProps"));
        long current = resourceFile.lastModified();
        if (current > lastModifiedTime) {
            java.io.InputStream dbPropsStream =  new FileInputStream(resourceFile );
            java.util.Properties dbProps = new java.util.Properites();
            dbProps.load(dbPropsStream);
            realoadDBProps();

        }
        lastModifiedTime = current;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

}
}
}
Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
1

That is a good idea to read the database values from properties file

You can use a properties class from Util package. The important thing to keep in mind is closing the stream after reading the file or writing the file to disk. Otherwise it causes problems. Here is an example for your reference:

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

public class App 
{
    public static void main( String[] args )
    {
        Properties prop = new Properties();

        try {
            //load a properties file
        prop.load(new FileInputStream("config.properties"));

            //get the property value and print it out
            System.out.println(prop.getProperty("database"));
        System.out.println(prop.getProperty("dbuser"));
        System.out.println(prop.getProperty("dbpassword"));

        } catch (IOException ex) {
        ex.printStackTrace();
        }

    }
}

Output

localhost
mkyong
password
Chris Farmer
  • 24,974
  • 34
  • 121
  • 164
Harish
  • 11
  • 2
1
ResourceBundle rb = ResourceBundle.getBundle("mybundle");
String propertyValue = rb.getString("key");

assuming mybundle.properties file is in classpath

Kalpesh Soni
  • 6,879
  • 2
  • 56
  • 59
1

The Properties class has a convenient load method. That's the easiest way to read a java properties file.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
  • But i used Properties method but it throws FileNotFound Exception My code : Properties prop = new Properties(); prop.load(new FileInputStream("file.properties")); – dean Jun 06 '11 at 06:42
0

Read this.Usually the properties file is kept in the classpath so that this method can read it.

Gyan aka Gary Buyn
  • 12,242
  • 2
  • 23
  • 26