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


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();
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM