讀文件很簡單:
- public static String getProperty(String key) {
- String value = "";
- //第一步是取得一個Properties對象
- Properties props = new Properties();
- //第二步是取得配置文件的輸入流
- InputStream is = PropUtil.class.getClassLoader().getResourceAsStream("config.properties");//在非WEB環境下用這種方式比較方便
- try {
- InputStream input = new FileInputStream("config.properties");//在WEB環境下用這種方式比較方便,不過當配置文件是放在非Classpath目錄下的時候也需要用這種方式
- //第三步講配置文件的輸入流load到Properties對象中,這樣在後面就可以直接取來用了
- props.load(input);
- value = props.getProperty(key);
- is.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return value;
- }
往配置文件裏面寫內容:
- public static void setProperty(Map<String,String> data) {
- //第一步也是取得一個Properties對象
- Properties props = new Properties();
- //第二步也是取得該配置文件的輸入流
- // InputStream is = PropUtil.class.getClassLoader().getResourceAsStream("config.properties");
- try {
- InputStream input = new FileInputStream("config.properties");
- //第三步是把配置文件的輸入流load到Properties對象中,
- props.load(input);
- //接下來就可以隨便往配置文件裏面添加內容了
- // props.setProperty(key, value);
- if (data != null) {
- Iterator<Entry<String,String>> iter = data.entrySet().iterator();
- while (iter.hasNext()) {
- Entry<String,String> entry = iter.next();
- props.setProperty(entry.getKey().toString(), entry.getValue().toString());
- }
- }
- //在保存配置文件之前還需要取得該配置文件的輸出流,<span style="color: #ff0000; font-size: medium;">切記,</span>如果該項目是需要導出的且是一個非WEB項目,則該配置文件應當放在根目錄下,否則會提示找不到配置文件
- OutputStream out = new FileOutputStream("config.properties");
- //最後就是利用Properties對象保存配置文件的輸出流到文件中;
- props.store(out, null);
- input.close();
- out.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }