讀取.properties配置文件(轉載)

 

讀取.properties 文件html

 配置文件的一種,內容以鍵值對的形式存在,且每一個鍵值對獨佔一行。#號做爲行註釋的起始標誌,中文註釋會自動進行unicode編碼。示例:

# ip and port of server socket
ip=127.0.0.1
port=9999
# error message
msg=I'm sorry, bye bye!

經過properties對象操做java

public class Demo{
  public static void main(String[] args){
    Properties props = new Properties();
    
    InputStream in = Demo.class.getResourceAsStream("../config.properties");

    // 或使用文件輸入流(不推薦),假設當前工做目錄爲bin
    //InputStream in = new FileInputStream("./config.properties");

    props.load(in);
    in.close();
    
    // 讀取特定屬性
    String key = "ip";
    String ip = props.getProperty(key);

    // 遍歷全部屬性,方式一
    Set keys = props.keySet();
    for (Interator it = keys.iterator(); it.hasNext();){
        String k = it.next();
        System.out.println(k + ":" + props.getProperty(k));
    }
     // 遍歷全部屬性,方式二
    Enumeration en = props.propertyNames();
    while (en.hasMoreElements()){
        String k = en.nextElement();
        System.out.println(k + ":" + props.getProperty(k));
    }
  }
}

 

   1. 經過 Demo.class.getResourceAsStream("../config.properties"); 讀取配置文件,配置文件的相對路徑以類文件所在目錄做爲當前目錄。

   2. 經過 new FileInputStream("./config.properties"); 讀取配置文件,配置文件的相對路徑以工做目錄(能夠經過 System.getProperty("user.dir") 獲取工做目錄)做爲當前目錄。

   注意:上述兩種方式獲取的配置文件均沒有被緩存。每次都要從新加載配置文件。

  寫屬性,示例:
複製代碼

Properties props = new Properties();
InputStream in = getClass().getResouceAsStream("properties文件相對於當前類加載路徑的文件目錄");
props.load(in);

OutputStream output = new FileOutputStream("properties文件路徑");
props.setProperty("ip", "10.248.112.123"); // 修改或新增屬性鍵值對
props.store(output, "modify ip value"); // store(OutputStream output, String comment)將修改結果寫入輸出流
output.close()

 

經過ResourceBundle 對象操做web

 經過該方式僅能讀取配置文件而已,不能進行寫操做。示例:
複製代碼

// ResourceBundle rb = ResourceBundle.getBundle("配置文件相對工程根目錄的相對路徑(不含擴展名)");
ResourceBundle rb = ResourceBundle.getBundle("config");
try{
    String name = rb.getString("name");
}
catch(MissingResourceException ex){

複製代碼

注意:上述方式會緩存配置文件信息,後續讀取時均是讀取緩存中的內容,若在此期間修改了配置內容是沒法實時同步的

ResourceBundle有兩個子類ListResourceBundle和PropertyResourceBundle,在讀取properties文件時其實是使用PropertyResourceBundle來處理。

題外話:

  ResourceBundle主要用於解決國際化和本地化問題。經過資源命名定義各語言和方言的信息,然乎程序在運行時獲取當前本地化信息,並根據本地化信息加載相應的資源完成本地化。

  資源命名規範:
複製代碼

// 僅含家族名
MyResource

// 含家族名和語言
MyResource_en

// 含家族名、語言和國家
MyResource_en_US

複製代碼

  對應的Java代碼:

// ResourceBundle首先會根據語言和國家的本地化信息去查找資源(假設如今要查找MyResource_zh_CN),當找不到時就會找MyResource_zh,再找不到就用MyResource。
ResourceBundle rb = ResourceBundle.getBundle("MyResource", Locale.getDefault())

 

java中的properties文件是一種配置文件,主要用於表達配置信息,文件類型爲*.properties,格式爲文本文件,文件的內容是格式是"鍵=值"的格式,在properties 文件中,能夠用"#"來做註釋,properties文件在Java編程中用到的地方不少,操做很方便。編程

1、properties文件緩存

test.properties
#   說明:業務系統TopIcis和報表系統IcisReport是分離的
#   可分開部署到不一樣的服務器上,也能夠部署到同一個服務
#   器上;IcisReprot做爲獨立的web應用程序可使用任何
#   的Servlet容器或者J2EE服務器部署並單獨運行,也能夠
#   經過業務系統的接口調用做爲業務系統的一個庫來應用.
#
#   IcisReport的ip
IcisReport.server.ip=192.168.3.143
#   IcisReport的端口
IcisReport.server.port=8080
#   IcisReport的上下文路徑
IcisReport.contextPath=/IcisReport

------------------------------------------------------ 
Properties類的重要方法
Properties 類存在於胞 Java.util 中,該類繼承自 Hashtable
1. getProperty ( String  key) ,   用指定的鍵在此屬性列表中搜索屬性。也就是經過參數 key ,獲得 key 所對應的 value。
2. load ( InputStream  inStream) ,從輸入流中讀取屬性列表(鍵和元素對)。經過對指定的文件(好比說上面的 test.properties 文件)進行裝載來獲取該文

件中的全部鍵 - 值對。以供 getProperty ( String  key) 來搜索。
3. setProperty ( String  key, String  value) ,調用 Hashtable 的方法 put 。他經過調用基類的put方法來設置 鍵 - 值對。 
4. store ( OutputStream  out, String  comments) ,   以適合使用 load 方法加載到 Properties 表中的格式,將此 Properties 表中的屬性列表(鍵和元素

對)寫入輸出流。與 load 方法相反,該方法將鍵 - 值對寫入到指定的文件中去。
5. clear () ,清除全部裝載的 鍵 - 值對。該方法在基類中提供。
-------------------------------

2、操做properties文件的java方法 

讀屬性文件
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("/IcisReport.properties");
prop.load(in);
Set keyValue = prop.keySet();
for (Iterator it = keyValue.iterator(); it.hasNext();)
{
String key = (String) it.next();
}
------------------------
outputFile = new FileOutputStream(fileName);
propertie.store(outputFile, description);
outputFile.close();
-----------------------------------------------------------------------------------------
Class.getResourceAsStream ("/some/pkg/resource.properties");
ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
java.util.ResourceBundle rs = java.util.ResourceBundle.getBundle("some.pkg.resource");
rs.getString("xiaofei");
-----------------------------------------------------------------------------------------
寫屬性文件
Configuration saveCf = new Configuration();
saveCf.setValue("min", "10");
saveCf.setValue("max", "1000");
saveCf.saveFile(".\config\save.perperties","test");

總結:java的properties文件須要放到classpath下面,這樣程序才能讀取到,有關classpath實際上就是java類或者庫的存放路徑,在java工程中,properties放到

class文件一塊。在web應用中,最簡單的方法是放到web應用的WEB- INF\classes目錄下便可,也能夠放在其餘文件夾下面,這時候須要在設置classpath環境變量的

時候,將這個文件夾路徑加到 classpath變量中,這樣也也能夠讀取到。在此,你須要對classpath有個深入理解,classpath絕非系統中刻意設定的那個系統環境變

量,WEB-INF\classes其實也是,java工程的class文件目錄也是。

發個例子你們本身看哈.
package control;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;

public class TestMain {
 
 //根據key讀取value
 public static String readValue(String filePath,String key) {
  Properties props = new Properties();
        try {
         InputStream in = new BufferedInputStream (new FileInputStream(filePath));
         props.load(in);
         String value = props.getProperty (key);
            System.out.println(key+value);
            return value;
        } catch (Exception e) {
         e.printStackTrace();
         return null;
        }
 }
 
 //讀取properties的所有信息
    public static void readProperties(String filePath) {
     Properties props = new Properties();
        try {
         InputStream in = new BufferedInputStream (new FileInputStream(filePath));
         props.load(in);
            Enumeration en = props.propertyNames();
             while (en.hasMoreElements()) {
              String key = (String) en.nextElement();
                    String Property = props.getProperty (key);
                    System.out.println(key+Property);
                }
        } catch (Exception e) {
         e.printStackTrace();
        }
    }

    //寫入properties信息
    public static void writeProperties(String filePath,String parameterName,String parameterValue) {
     Properties prop = new Properties();
     try {
      InputStream fis = new FileInputStream(filePath);
            //從輸入流中讀取屬性列表(鍵和元素對)
            prop.load(fis);
            //調用 Hashtable 的方法 put。使用 getProperty 方法提供並行性。
            //強制要求爲屬性的鍵和值使用字符串。返回值是 Hashtable 調用 put 的結果。
            OutputStream fos = new FileOutputStream(filePath);
            prop.setProperty(parameterName, parameterValue);
            //以適合使用 load 方法加載到 Properties 表中的格式,
            //將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流
            prop.store(fos, "Update '" + parameterName + "' value");
        } catch (IOException e) {
         System.err.println("Visit "+filePath+" for updating "+parameterName+" value error");
        }
    }

    public static void main(String[] args) {
     readValue("info.properties","url");
        writeProperties("info.properties","age","21");
        readProperties("info.properties" );
        System.out.println("OK");
    }

 發個例子你們本身看哈.

package control;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;

public class TestMain {
 
 //根據key讀取value
 public static String readValue(String filePath,String key) {
  Properties props = new Properties();
        try {
         InputStream in = new BufferedInputStream (new FileInputStream(filePath));
         props.load(in);
         String value = props.getProperty (key);
            System.out.println(key+value);
            return value;
        } catch (Exception e) {
         e.printStackTrace();
         return null;
        }
 }
 
 //讀取properties的所有信息
    public static void readProperties(String filePath) {
     Properties props = new Properties();
        try {
         InputStream in = new BufferedInputStream (new FileInputStream(filePath));
         props.load(in);
            Enumeration en = props.propertyNames();
             while (en.hasMoreElements()) {
              String key = (String) en.nextElement();
                    String Property = props.getProperty (key);
                    System.out.println(key+Property);
                }
        } catch (Exception e) {
         e.printStackTrace();
        }
    }

    //寫入properties信息
    public static void writeProperties(String filePath,String parameterName,String parameterValue) {
     Properties prop = new Properties();
     try {
      InputStream fis = new FileInputStream(filePath);
            //從輸入流中讀取屬性列表(鍵和元素對)
            prop.load(fis);
            //調用 Hashtable 的方法 put。使用 getProperty 方法提供並行性。
            //強制要求爲屬性的鍵和值使用字符串。返回值是 Hashtable 調用 put 的結果。
            OutputStream fos = new FileOutputStream(filePath);
            prop.setProperty(parameterName, parameterValue);
            //以適合使用 load 方法加載到 Properties 表中的格式,
            //將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流
            prop.store(fos, "Update '" + parameterName + "' value");
        } catch (IOException e) {
         System.err.println("Visit "+filePath+" for updating "+parameterName+" value error");
        }
    }

    public static void main(String[] args) {
     readValue("info.properties","url");
        writeProperties("info.properties","age","21");
        readProperties("info.properties" );
        System.out.println("OK");
    }
}

 

本文轉載於:http://www.cnblogs.com/fsjohnhuang/p/3995386.html服務器

相關文章
相關標籤/搜索