Chan Chen Coding...

Java Properties file examples

In Java, properties file is always used to store the configuration data or settings. In this example we will show you how to read and write to/from a properties file.

1. Example 1

In this example, set the property value and write it into a properties file named “config.properties“. The new saved properties file will be stored at your project root folder.

package com.mkyong.common;   
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;  
public class App {
    public static void main( String[] args )
    {
        Properties prop = new Properties();
  try {
//set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "mkyong");
prop.setProperty("dbpassword", "password");
  //save properties to project root folder
prop.store(new FileOutputStream("config.properties"), null);
  } catch (IOException ex) {
ex.printStackTrace();
}
}
}

Output – The content of the file “config.properties

#Mon Jan 11 18:54:40 MYT 2010 
dbpassword=password
database=localhost
dbuser=mkyong

2. Example 2

In this 2nd example, load a properties file named “config.properties” and retrieved the saved property value.

package com.mkyong.common;   
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


-----------------------------------------------------
Silence, the way to avoid many problems;
Smile, the way to solve many problems;

posted on 2012-06-07 13:05 Chan Chen 阅读(359) 评论(0)  编辑  收藏 所属分类: Scala / Java


只有注册用户登录后才能发表评论。


网站导航: