Propertiesプロファイルの読み込み/書き込み例

2054 ワード

 :test.properties

 :domain=www.test.com

JAvaコード:
package com.test;

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

public class DomainUtil {
	private static DomainUtil util = null;
	private static Properties props = null;
	private static String PROP_LOCATION = "/test.properties";

	private DomainUtil() {

	}

	public static final DomainUtil getInstance() {
		try {
			if (util == null) {
				loadFile(PROP_LOCATION);
				util = new DomainUtil();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return util;
	}

	private static void loadFile(String path) throws IOException {
		props = new Properties();
		InputStream inStream = DomainUtil.class.getResourceAsStream(path);
		props.load(inStream);
	}

	public String getDomainValue(String key) {
		if (props == null && props.isEmpty())
			return "";
		return props.getProperty(key);
	}

	public static void main(String[] args) {
		System.out.println(DomainUtil.getInstance().getDomainValue("domain"));
                String appTitle = "app_title";
                String appVersion = "app_version";
                String appProperties = "app.properties";

                Properties settings = new Properties();
                settings.put(appTitle, " ");
                settings.put(appVersion, "1.0");

        try {
            
            // 
            FileOutputStream out = new FileOutputStream(appProperties);
            settings.store(out, "AppConfig");

            // 
            FileInputStream in = new FileInputStream(appProperties);
            settings.load(in);
            
            String title = settings.getProperty(appTitle);
            String version = settings.getProperty(appVersion);
            
            System.out.println(title + "\t" + version);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
 }}