溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java讀取Properties文件的七種方法的總結(jié)

發(fā)布時(shí)間:2020-10-01 18:59:05 來源:腳本之家 閱讀:139 作者:lqh 欄目:編程語言

Java讀取Properties文件的方法總結(jié)

         讀取.properties配置文件在實(shí)際的開發(fā)中使用的很多,總結(jié)了一下,有以下幾種方法:

其實(shí)很多都是大同小異,概括起來就2種:

先構(gòu)造出一個(gè)InputStream來,然后調(diào)用Properties#load()

利用ResourceBundle,這個(gè)主要在做國際化的時(shí)候用的比較多。

例如:它能根據(jù)系統(tǒng)語言環(huán)境自動(dòng)讀取下面三個(gè)properties文件中的一個(gè):

  • resource_en_US.properties
  • resource_zh_CN.properties
  • resource.properties

 附上別人整理的6中方法...

1、使用java.util.Properties類的load()方法

InputStream in = new BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);

2、使用java.util.ResourceBundle類的getBundle()方法

ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());

3、使用java.util.PropertyResourceBundle類的構(gòu)造函數(shù)

InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);

4、使用class變量的getResourceAsStream()方法

InputStream in = JProperties.class.getResourceAsStream(name);//JProperties為當(dāng)前類名
Properties p = new Properties();
p.load(in);

5、使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法

InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

6、使用java.lang.ClassLoader類的getSystemResourceAsStream()靜態(tài)方法

InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);

7、在Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法

InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI