日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

Java Properties 類讀取配置文件信息

 WindySky 2009-02-18

在我們平時(shí)寫程序的時(shí)候,有些參數(shù)是經(jīng)常改變的,而這種改變不是我們預(yù)知的。比如說我們開發(fā)了一個(gè)操作數(shù)據(jù)庫(kù)的模塊,在開發(fā)的時(shí)候我們連接本地的數(shù)據(jù)庫(kù)那么 IP ,數(shù)據(jù)庫(kù)名稱,表名稱,數(shù)據(jù)庫(kù)主機(jī)等信息是我們本地的,要使得這個(gè)操作數(shù)據(jù)的模塊具有通用性,那么以上信息就不能寫死在程序里。通常我們的做法是用配置文件來解決。

各種語(yǔ)言都有自己所支持的配置文件類型。比如 Python ,他支持 .ini 文件。因?yàn)樗麅?nèi)部有一個(gè) ConfigParser 類來支持 .ini 文件的讀寫,根據(jù)該類提供的方法程序員可以自由的來操作 .ini 文件。而在 Java 中, Java 支持的是 .properties 文件的讀寫。 JDK 內(nèi)置的 java.util.Properties 類為我們操作 .properties 文件提供了便利。

 

一. .properties 文件的形式 ==========================================================

 

 

# 以下為服務(wù)器、數(shù)據(jù)庫(kù)信息

dbPort = localhost

databaseName = mydb

dbUserName = root

dbPassword = root

# 以下為數(shù)據(jù)庫(kù)表信息

dbTable = mytable

# 以下為服務(wù)器信息

ip = 192.168.0.9

······

在上面的文件中我們假設(shè)該文件名為: test.properties 文件。其中 # 開始的一行為注釋信息;在等號(hào)“ = ”左邊的我們稱之為 key ;等號(hào)“ = ”右邊的我們稱之為 value 。(其實(shí)就是我們常說的鍵 - 值對(duì)) key 應(yīng)該是我們程序中的變量。而 value 是我們根據(jù)實(shí)際情況配置的。

 

二. JDK 中的 Properties Properties 類存在于胞 Java.util 中,該類繼承自 Hashtable ,它提供了幾個(gè)主要的方法: 1. getProperty ( String  key)   用指定的鍵在此屬性列表中搜索屬性。也就是通過參數(shù) key ,得到 key 所對(duì)應(yīng)的 value 。

 

 

 

2. load ( InputStream  inStream) ,從輸入流中讀取屬性列表(鍵和元素對(duì))。通過對(duì)指定的文件(比如說上面的 test.properties 文件)進(jìn)行裝載來獲取該文件中的所有鍵 - 值對(duì)。以供 getProperty ( String  key) 來搜索。 3. setProperty ( String  key, String  value) ,調(diào)用 Hashtable 的方法 put 。他通過調(diào)用基類的put方法來設(shè)置 - 值對(duì)。

 

4. store ( OutputStream  out, String  comments) ,   以適合使用 load 方法加載到 Properties 表中的格式,將此 Properties 表中的屬性列表(鍵和元素對(duì))寫入輸出流。與 load 方法相反,該方法將鍵 - 值對(duì)寫入到指定的文件中去。

5. clear () ,清除所有裝載的 - 值對(duì)。該方法在基類中提供。

有了以上幾個(gè)方法我們就可以對(duì) .properties 文件進(jìn)行操作了!

三.代碼實(shí)例

 

 
package configuration;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 讀取properties文件
 * 
@author Qutr
 *
 
*/

public class Configuration
{
    
private Properties propertie;
    
private FileInputStream inputFile;
    
private FileOutputStream outputFile;
    
    
/**
     * 初始化Configuration類
     
*/

    
public Configuration()
    
{
        propertie 
= new Properties();
    }

    
    
/**
     * 初始化Configuration類
     * 
@param filePath 要讀取的配置文件的路徑+名稱
     
*/

    
public Configuration(String filePath)
    
{
        propertie 
= new Properties();
        
try {
            inputFile 
= new FileInputStream(filePath);
            propertie.load(inputFile);
            inputFile.close();
        }
 catch (FileNotFoundException ex) {
            System.out.println(
"讀取屬性文件--->失?。? 原因:文件路徑錯(cuò)誤或者文件不存在");
            ex.printStackTrace();
        }
 catch (IOException ex) {
            System.out.println(
"裝載文件--->失敗!");
            ex.printStackTrace();
        }

    }
//end ReadConfigInfo(...)
    
    
/**
     * 重載函數(shù),得到key的值
     * 
@param key 取得其值的鍵
     * 
@return key的值
     
*/

    
public String getValue(String key)
    
{
        
if(propertie.containsKey(key)){
            String value 
= propertie.getProperty(key);//得到某一屬性的值
            return value;
        }

        
else 
            
return "";
    }
//end getValue(...)
    
    
/**
     * 重載函數(shù),得到key的值
     * 
@param fileName properties文件的路徑+文件名
     * 
@param key 取得其值的鍵
     * 
@return key的值
     
*/

    
public String getValue(String fileName, String key)
    
{
        
try {
            String value 
= "";
            inputFile 
= new FileInputStream(fileName);
            propertie.load(inputFile);
            inputFile.close();
            
if(propertie.containsKey(key)){
                value 
= propertie.getProperty(key);
                
return value;
            }
else
                
return value;
        }
 catch (FileNotFoundException e) {
            e.printStackTrace();
            
return "";
        }
 catch (IOException e) {
            e.printStackTrace();
            
return "";
        }
 catch (Exception ex) {
            ex.printStackTrace();
            
return "";
        }

    }
//end getValue(...)
    
    
/**
     * 清除properties文件中所有的key和其值
     
*/

    
public void clear()
    
{
        propertie.clear();
    }
//end clear();
    
    
/**
     * 改變或添加一個(gè)key的值,當(dāng)key存在于properties文件中時(shí)該key的值被value所代替,
     * 當(dāng)key不存在時(shí),該key的值是value
     * 
@param key 要存入的鍵
     * 
@param value 要存入的值
     
*/

    
public void setValue(String key, String value)
    
{
        propertie.setProperty(key, value);
    }
//end setValue(...)
    
    
/**
     * 將更改后的文件數(shù)據(jù)存入指定的文件中,該文件可以事先不存在。
     * 
@param fileName 文件路徑+文件名稱
     * 
@param description 對(duì)該文件的描述
     
*/

    
public void saveFile(String fileName, String description)
    
{
        
try {
            outputFile 
= new FileOutputStream(fileName);
            propertie.store(outputFile, description);
            outputFile.close();
        }
 catch (FileNotFoundException e) {
            e.printStackTrace();
        }
 catch (IOException ioe){
            ioe.printStackTrace();
        }

    }
//end saveFile(...)
    
    
public static void main(String[] args)
    
{
        Configuration rc 
= new Configuration(".\config\test.properties");//相對(duì)路徑
        
        String ip 
= rc.getValue("ipp");//以下讀取properties文件的值
        String host = rc.getValue("host");
        String tab 
= rc.getValue("tab");
        
        System.out.println(
"ip = " + ip + "ip-test leng = " + "ip-test".length());//以下輸出properties讀出的值
        System.out.println("ip's length = " + ip.length());
        System.out.println(
"host = " + host);
        System.out.println(
"tab = " + tab);

        Configuration cf 
= new Configuration();
        String ipp 
= cf.getValue(".\config\test.properties""ip");
        System.out.println(
"ipp = " + ipp);
//        cf.clear();
        cf.setValue("min""999");
        cf.setValue(
"max""1000");
        cf.saveFile(
".\config\save.perperties""test");
        
//        Configuration saveCf = new Configuration();
//        saveCf.setValue("min", "10");
//        saveCf.setValue("max", "1000");
//        saveCf.saveFile(".\config\save.perperties");
        
    }
//end main()
    
}
//end class ReadConfigInfo

四.小結(jié) 通過上面的例子不難看出,在Java中操作配置文件是非常簡(jiǎn)單的。在一個(gè)需要用到大量配置信息的模塊或系統(tǒng)里,我們有必要封裝一個(gè)專門的類來共使用。通過最后的main函數(shù)調(diào)用,相信大家可以看出該類的用法。不足指出希望大家多多指點(diǎn)。

 

 Java properties文件的操作 




       java中的properties文件是一種配置文件,主要用于表達(dá)配置信息,文件類型為*.properties,格式為文本文件,文件的內(nèi)容是格式是 "鍵=值"的格式,在properties文件中,可以用"#"來作注釋,properties文件在Java編程中用到的地方很多,操作很方便。下面是 一個(gè)操作java properties文件的例子,給出了操作方法和properties文件。從中可以看到如何讀取properties文件,并應(yīng)用讀取出來的值,是學(xué) 習(xí)操作properties文件的好例子。

一、properties文件

IcisReport.properties
------------------------------------------------------
###################################################
#   工商報(bào)表應(yīng)用IcisReport的配置文件               #
#   作者:雷智民                                   #
#   日期:2006年11月21日                           #
###################################################
#
#   說明:業(yè)務(wù)系統(tǒng)TopIcis和報(bào)表系統(tǒng)IcisReport是分離的
#   可分開部署到不同的服務(wù)器上,也可以部署到同一個(gè)服務(wù)
#   器上;IcisReprot作為獨(dú)立的web應(yīng)用程序可以使用任何
#   的Servlet容器或者J2EE服務(wù)器部署并單獨(dú)運(yùn)行,也可以
#   通過業(yè)務(wù)系統(tǒng)的接口調(diào)用作為業(yè)務(wù)系統(tǒng)的一個(gè)庫(kù)來應(yīng)用.
#
#   IcisReport的ip
IcisReport.server.ip=192.168.3.143
#   IcisReport的端口
IcisReport.server.port=8080
#   IcisReport的上下文路徑
IcisReport.contextPath=/IcisReport

------------------------------------------------------

 

二、操作properties文件的java方法

 

下面是一個(gè)操作properties文件的方法

------------------------------------------------------
    /**
     * @return 獲取IcisReport報(bào)表應(yīng)用的URL
     */
    private String getIcisReportURL() {
        String icisReportURL = "";              //IcisReport報(bào)表應(yīng)用的URL
        String icisReportServerIP = "";         //IcisReport服務(wù)器的IP
        String icisReportServerPort = "";       //IcisReport服務(wù)器的服務(wù)端口
        String icisReportContextPath="";        //IcisReport應(yīng)用的ContextPath

        Properties prop = new Properties();
        InputStream in;
        try {
            in = getClass().getResourceAsStream("/IcisReport.properties");
            prop.load(in);
            Set keyValue = prop.keySet();
            for (Iterator it = keyValue.iterator(); it.hasNext();) {
                String key = (String) it.next();
                if (key.equals("IcisReport.server.ip")) {
                    icisReportServerIP = (String) prop.get(key);
                } else if (key.equals("IcisReport.server.port")) {
                    icisReportServerPort = (String) prop.get(key);
                } else if (key.equals("IcisReport.contextPath")){
                    icisReportContextPath=(String) prop.get(key);
                }
            }
        } catch (Exception e) {
            log.error("IO讀取出錯(cuò),找不到IcisReport.properties!");
        }

        if (icisReportServerIP.trim().equals("")) {
            log.error("請(qǐng)檢查配置文件IcisReport.properties中的IcisReport.server.ip項(xiàng)的值是否正確!");
        }
        if (icisReportServerPort.trim().equals("")) {
            log.error("請(qǐng)檢查配置文件IcisReport.properties中的IcisReport.server.port項(xiàng)的值是否正確!");
        }
        if (icisReportServerPort.trim().equals("")) {
            log.error("請(qǐng)檢查配置文件IcisReport.properties中的IcisReport.server.port項(xiàng)的值是否正確!");
        }

        icisReportURL = "http://" + icisReportServerIP.trim() + ":" + icisReportServerPort.trim()+icisReportContextPath.trim();
        log.info("獲取的icisReportURL=" + icisReportURL);
        return icisReportURL;
    }

------------------------------------------------------

 

總 結(jié):java的properties文件需要放到classpath下面,這樣程序才能讀取到,有關(guān)classpath實(shí)際上就是java類或者庫(kù)的存放 路徑,在java工程中,properties放到class文件一塊。在web應(yīng)用中,最簡(jiǎn)單的方法是放到web應(yīng)用的WEB-INF\classes 目錄下即可,也可以放在其他文件夾下面,這時(shí)候需要在設(shè)置classpath環(huán)境變量的時(shí)候,將這個(gè)文件夾路徑加到classpath變量中,這樣也也可 以讀取到。在此,你需要對(duì)classpath有個(gè)深刻理解,classpath絕非系統(tǒng)中刻意設(shè)定的那個(gè)系統(tǒng)環(huán)境變量,WEB-INF\classes其 實(shí)也是,java工程的class文件目錄也是。

 

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多