java 读取配置文件

一、properties 文件:

name=yaokangjun
age=12

位置为根目录:

java 读取配置文件

二、demo:

package com.yao.properties;

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

/**
 * Created by Kangjun on 2015/11/26.
 */
public class Demo {
    private static final String FILE_NAME = "person.properties";
    private static Properties properties = null;
    static {
        properties = new Properties();
        InputStream is = null;
        try {
            String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            is = new FileInputStream(path + FILE_NAME);
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public static String getValue(String key){
        return (String)properties.get(key);
    }
    public static void main(String[] args) {
        String name = getValue("name");
        int age = Integer.parseInt(getValue("age"));
        System.out.println("name:"+name + ",age:"+age);

        String love = getValue("love");//不存在的
        System.out.println("Love:" + love);
    }
}

三、运行的结果为:

name:yaokangjun,age:12
Love:null


你可能感兴趣的:(properties,配置)