2011-12-12 97 views
3

我的應用程序有很多屬性/文本配置文件。有沒有一種常見的方法來驗證這些類型的文件?可能是一些工具或類似xsd? 文件很大(超過1000行),所以我經常犯錯。大多數情況下文件中的信息 - 是通向不同目錄的路徑。所以如果它們存在並且一致,那將會很好。例如。 如果我有如何驗證屬性/自定義配置文件?

mydata.root="c:\data" 

後,我有:

myreports=${mydata.root}/reports 

,這將是很好的檢查是c:\ data,而C:\ DATA \報告存在

,並沒有寫入(有些數百行)例如

myreports=${mdata.root}/reports 
+0

這個'$ {}'的東西只適用於Ant進程;也就是說,如果它位於Ant進程之外,它不能從簡單的'.properties'文件中運行。它不會使用Java'Properties'類的'load()'方法。無論如何,你可以在Ant進程中檢查文件/文件夾的存在性,如下所示[http://stackoverflow.com/questions/1163998/do-i-have-any-way-to-check-the-existence-of -a-目錄中,螞蟻不-A-文件(http://stackoverflow.com/questions/1163998/do-i-have-any-way-to-check-the-existence-of-a-目錄在螞蟻不是一個文件) – ecle

回答

5

你可以在你的構建文件中做這個驗證。

例如,以下構建文件定義了一個macrodefvalidate-file-property,它驗證指定的屬性是否已定義,並且是否存在文件系統中的文件或目錄。

<project default="init"> 

    <property file="test.properties"/> 

    <target name="init"> 
    <validate-file-property property="program.files" type="dir"/> 
    <validate-file-property property="mydata.root" type="dir"/> 
    <validate-file-property property="foo"/> 
    </target> 

    <macrodef name="validate-file-property"> 
    <attribute name="property"/> 
    <attribute name="type" default="file"/> 
    <sequential> 
     <fail unless="@{property}" message="The property '@{property}' is undefinded."/> 
     <available file="${@{property}}" property="@{property}.exists" type="@{type}"/> 
     <fail unless="@{property}.exists" message="The @{type} '@{property}' with value '${@{property}}' does not exist."/> 
    </sequential> 
    </macrodef> 

</project> 

你需要決定何時驗證屬性,你需要明確驗證它們 - 因爲顯示在這個例子中,init目標。

順便說一句,如果您使用標準化模式來命名涉及文件或目錄的屬性 - 例如my.special.filemy.build.dir - 然後您可以使用shell腳本來發現所有相關屬性並編寫所有validate-file-property元素。例如:

awk -F= '/\.(file|dir)/{ printf "<validate-file-property property=\"%s\" type=\"%s\"/>\n", $1, gensub(/.*\.(file|dir)/, "\\1", "g", $1) }' *.properties 

您可以將輸出粘貼到您的構建文件中。

+0

+1:偉大的答案! –

1

我曾經提供過關於提供模式驗證的除XML以外的配置語言信息的賞金。不幸的是,這種配置語言很少。

這是一個link以回報的問題,如果你想看到的反應稀疏。

相關問題