liguofeng29’s blog

個人勉強用ブログだっす。

Get Properties from File.

package org.lee.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;

public class PropertyUtil {

    private Properties getProperties(String path) {
        Properties conf = new Properties();
        InputStream inputStream = null;

        try {
            inputStream = new FileInputStream(new File(path));
            conf.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return conf;
    }

    public static void main(String[] args) {
        PropertyUtil util = new PropertyUtil();
        Properties p = util.getProperties("ppp.conf");
        
        // 方法1
        Enumeration<?> en = p.propertyNames();
        while (en.hasMoreElements()) {
            String key = (String) en.nextElement();
            System.out.println(key + "=" + p.get(key));
        }
        
        // 方法2
        Iterator<?> it = p.keySet().iterator();
        while (it.hasNext()) {
          String key = (String)it.next();
          System.out.println(key + "=" + p.get(key));
        }
    }
}
b=2
a=1
b=2
a=1

※うん・・順序は保持してくれないね。