2013年1月30日 星期三

[Java] Config Parser

1. Class Name
    java.util.Properties

2. Description
如果需要使用到Config Parser,可使用這個Class來完成。

3. Example
@network.cfg
address=192.168.11.11
network=255.255.255.0
gateway=192.168.11.1

@SourceCode
package sample.properties;
import java.io.*;
import java.util.Properties;

public class SampleProperties {

  private static Properties props;

  private static void loadConfig(String cfgPath) {
    props = new Properties();
    try {
      props.load(new FileInputStream(cfgPath));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static String getProperty(String key) {
    return props.getProperty(key);
  }

  public static void main(String[] args) {
    loadConfig("network.cfg");
    String address = getProperty("address");
    String network = getProperty("network");
    String gateway = getProperty("gateway");
    System.out.println("address : " + address );
    System.out.println("network : " + network);
    System.out.println("gateway : " + gateway);

  }
}

4. Output
address : 192.168.11.11
network : 255.255.255.0
gateway : 192.168.11.1

沒有留言:

張貼留言