代码改变世界

java配置文件properties,yml,一般文件

2018-07-26 20:44  ZealouSnesS  阅读(4544)  评论(0编辑  收藏  举报

JAVA编写配置文件的几种方式:

 

JAVA配置文件,一般都放在resource目录下,无论是下面提到的properties、yml还是普通的txt等文件。

在打成jar包之后,只需要jar包程序就可运行,如果要修改配置文件,只需将配置文件放在与jar包同一目录下即可,jar包会自动读取。

 

1、properties文件

配置文件里面写好你要用的配置值:

 

创建获取properties对象的函数:

public static Properties loadPropertiesFromFile(String filename) throws IOException {
        Properties p = new Properties();
        InputStream input = Downloader.class.getClassLoader().getResourceAsStream(filename);
        p.load(input);
        return p;
    }

 

代码中调用配置量:

Properties p = loadPropertiesFromFile("downloader.properties");
String regex=p.getProperty("local_ip_regex");

 

 

2、yml文件

配置文件里面配置值的方式与properties类似,也是用 变量名=值 的方式,但是中间可以用----隔开,然后yml会自动将两个-------之间的内容解析为一个map

一个yml文件解析出来就是一个List<Map>

 

3、直接读取文件转化为String或InputStream

参考:、

java中读取resources目录下的配置文件:https://blog.csdn.net/xu511739113/article/details/52440982

使用inputstream按行读取文件:https://blog.csdn.net/u010889616/article/details/51477037

    public static  InputStream get_whitelist_inputstream(){
        //获取配置文件的inputstream
        ClassLoader classLoader=Downloader.class.getClassLoader();
        InputStream whitelist_inputstream=classLoader.getResourceAsStream(p.getProperty("white_list_file"));
        return whitelist_inputstream;

        //获取配置文件的路径名
//        ClassLoader classLoader=Downloader.class.getClassLoader();
//        URL resource=classLoader.getResource(p.getProperty("white_list_file"));
//        String path=resource.getPath();
    }