如何使用ant build从属性文件中删除注释的属性?

时间:2018-12-27 14:21:40

标签: java ant properties-file

我想通过ant build从属性文件中删除注释的属性。为了安全起见,我不想在沙盒服务器上公开我的生产属性。

属性文件:

#production properties
#redis.master.url=redis.prod.master.compny.com
#redis.slave.url=redis.prod.slave.compny.com

#sandboxproperties
redis.master.url=redis.sandbox.master.compny.com
redis.slave.url=redis.sandbox.slave.compny.com

所以,我的war软件包应该具有以下属性文件:

redis.master.url=redis.sandbox.master.compny.com
redis.slave.url=redis.sandbox.slave.compny.com

3 个答案:

答案 0 :(得分:0)

根据Ant docs

  

Apache Ant提供了一个用于编辑属性文件的可选任务。想要对应用程序服务器和应用程序的配置文件进行无人看管的修改时,这非常有用。当前,该任务维护着一个工作的属性文件,该文件可以添加属性或对现有属性进行更改。 由于Ant 1.8.0保留了原始属性文件的注释和布局。

因此,根据您使用的是哪个版本的ant构建,您也许可以从属性文件中删除注释。

答案 1 :(得分:0)

您可以使用ant中的脚本来做到这一点

<macrodef name="remove-properties-comments">
    <attribute name="inFile" />
    <attribute name="outFile" />
    <sequential>
        <script language="javascript">
            <![CDATA[
                // get the arguments
                var inFile = "@{inFile}"
                var outFile = "@{outFile}"

                // or get properties from the ant environment
                // eg: <property name="property.from.ant.project" value="value" />
                // var antProp = project.getProperty("property.from.ant.project");

                // load Java types
                var File = Java.type("java.io.File")
                var PrintWriter = Java.type("java.io.PrintWriter")
                var Scanner = Java.type("java.util.Scanner")

                // init reader and writer
                var reader = new Scanner(new File(inFile))
                var writer = new PrintWriter(outFile)

                // if previous line ended in '\' then it is a muliline property
                // so the following line should always be included
                var multiline = false
                while (reader.hasNextLine()) {
                    var line = reader.nextLine();
                    // you could exclude blank lines too if you want
                    if (multiline || !(line.startsWith("#") || line.startsWith("!"))) {
                        writer.println(line);
                    }
                    multiline = line.endsWith("\\");
                }
               ]]>
        </script>
    </sequential>
</macrodef>

<target name="test">
    <remove-properties-comments inFile="path/to/inFile.properties" outFile="path/to/outFile.properties" />
</target>

答案 2 :(得分:0)

我只是通过使用replaceregexp来解决这个问题。

<target>
    <replaceregexp match="\n#(.*)" replace="" flags="g" byline="false">
        <fileset dir="${build.home}/WEB-INF/classes" includes="**/*.properties" />
    </replaceregexp>
</target>

此处\n#(.*)<newline>\n)匹配,后跟#,后跟任意字符集(*)。

相关问题