Vijay Shanker Dubey
Vijay Shanker Dubey

Reputation: 4418

How do I append some text at the end of a file using Ant?

In one of the configuration files for my project I need to append some text. I am looking for some options to do this using Ant.

I have found one option - to find something and replace that text with the new text, and the old values. But it does not seems to be promising, as if in future someone changes the original file the build will fail.

So, I would like my script to add the text at the end of the file.

What options do I have for such a requirement?

Upvotes: 26

Views: 38334

Answers (4)

James Oravec
James Oravec

Reputation: 20391

I found the other answers useful, but not giving the flexibility I needed. Below is an example of writing echos to temp file that can be used as a header and footer, then using concatenation to wrap an xml document.

    <!-- Make header and footer for concatenation -->
    <echo file="header.txt"  append="true">
        <![CDATA[
            <?xml version='1.0' encoding='UTF-8'?>
            <!DOCTYPE foo ...>
        ]]>
    </echo>
    <echo file="footer.txt"  append="true">
        <![CDATA[
            </foo>
        ]]>
    </echo>

    <concat destfile="bigxml.xml">
        <fileset file="header.txt" />
        <fileset file="bigxml-without-wrap.xml" />
        <fileset file="footer.txt" />
    </concat>
    <delete file="header.txt"/>
    <delete file="footer.txt"/>

Upvotes: 2

Peter Walkley
Peter Walkley

Reputation: 101

The concat task would look to do it as well. See http://ant.apache.org/manual/Tasks/concat.html for examples, but the pertinent one is:

<concat destfile="README" append="true">Hello, World!</concat>

Upvotes: 8

martin clayton
martin clayton

Reputation: 78115

Another option would be to use a filterchain.

For example, the following will append file input2.txt to input1.txt and write the result to output.txt. The line separators for the current operating system (from the java properties available in ant) are used in the output file. Before using this you would have to create output2.txt on the fly I guess.

<copy file="input1.txt" tofile="output.txt" >
    <filterchain>
        <concatfilter append="input2.txt" />
        <tokenfilter delimoutput="${line.separator}" />
    </filterchain>
</copy>

Upvotes: 8

Michael Pilat
Michael Pilat

Reputation: 6520

Use the echo task:

<echo file="file.txt" append="true">Hello World</echo>

EDIT: If you have HTML (or other arbitrary XML) you should escape it with CDATA:

<echo file="file.txt" append="true">
<![CDATA[
  <h1>Hello World</h1>
]]>
</echo>

Upvotes: 50

Related Questions