2019/03/18

Java Read properties

專案結構



Score.properties:

name=TuWa
math=80
chine=75
en=69

Code:

import java.io.*;
import java.util.Properties;

public class Test {

    private static Properties properties = new Properties();

    static {
        final InputStream inputStream = Redis.class.getClassLoader().getResourceAsStream("Config.properties");
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        final String NAME = properties.getProperty("name", "王大狗");
        final int MATH = Integer.parseInt(properties.getProperty("math", "0"));
        final int CHINE = Integer.parseInt(properties.getProperty("chine", "0"));
        final int EN = Integer.parseInt(properties.getProperty("en", "0"));
        System.out.printf("Name:%s Math:%d Chine:%d EN:%d\n", NAME, MATH, CHINE, EN);
    }
}

執行結果: