Java 项目中的.properties文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZZh1301051836/article/details/79522977

1 创建.properties文件

下面将文件命名为config.properties:
工程目录结构

文件中的数据格式:
文件中的数据格式

2 读取文件中的数据

可以建立一个工具类,以便实现代码重用,下面将工具类命名为Utils.java:

package stephen.utils;

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

public class Utils {    
    public static class _property{
        public static int getCountAnswer(){
            Integer countAnswer = -1;
            Properties properties = new Properties();
            InputStream in=Utils.class.getClassLoader().getResourceAsStream("config.properties");

            try {
                properties.load(in);
                countAnswer = Integer.valueOf(properties.get("countAnswer").toString());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return countAnswer;         
        }

        public static int getcountDelLexicon(){
            Integer countDelLexicon = -1;
            Properties properties = new Properties();
            InputStream in = Utils.class.getClassLoader().getResourceAsStream("config.properties");

            try {
                properties.load(in);
                countDelLexicon = Integer.valueOf(properties.get("countDelLexicon").toString());
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

            return countDelLexicon;
        }
    }
}

使用上述工具类读取数据:

Integer countAnswer = Utils._property.getCountAnswer();

猜你喜欢

转载自blog.csdn.net/ZZh1301051836/article/details/79522977