Monday, March 3, 2008

Use of Property in JAVA

Generally we are familier to put our Database connection string
into the Base Dao...And we can change it while deploying.

but what happen while we want to change it at run time...

Best Solution is to
use properties of Java API.

====================================================
First create File name "sample.properties" in your project folder or at C:\
aas your conviency but remember that will hard coded in Program so make sure u type
path correctly in ur program

Crete following file name with data as shown after inside tab:

sample.properies

#This is property starting
# Owner Joshi Shirin

db.user=shirin
db.password=123456

# You can type any number of property and save it at c:\

=====================================================

Now Demostration of Java program which will print and update the File with other data..


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

/**
 * demonstratrate the use of java.util.Properties
 * @author Joshi Shirin
 */

public class TestProperties {

 // --------------------------- main() method ---------------------------

 /**
  * @throws IOException
  *             Let Java report any problem.
  */
 public static void main(String[] args) throws IOException {
  Properties props = new Properties();
  FileInputStream fis = new FileInputStream("C:/sample.properties");
  props.load(fis);
  fis.close();
  String desc_user = props.getProperty("db.user");

  System.out.println(desc_user);

  // Comment if not want to change the property file....

  // changing a property and saving the properties
  props.setProperty("db.password", "143143");

  FileOutputStream fos = new FileOutputStream(
    "C:/updated_sample.properties");

  /* saving will lose your comments, lose blank lines, and scramble the
  order. */
  

  props.store(fos,
    "sample properties with comments lost by Joshi Shirin");
  fos.close();
 }
}

No comments:

Contributors