13

Possible Duplicate:
Ant task to check if a file exists?

How can one check if a file exist in a directory, if not use another file in different location. I tried the follow but does not help me with what I want. Could someone help?

 <condition property="somefile.available">
     <or>
         <available file="/home/doc/somefile"/>
         <and>
             <available file="/usr/local/somefile" />
         </and>
     </or>
 </condition>
ShuMing Li
  • 153
  • 1
  • 8
user87636
  • 133
  • 1
  • 1
  • 5

2 Answers2

21

Use condition tests to establish if files are present. Then have a target for each true condition

<target name="go" depends="file-checks, do-something-with-first-file, do-something-with-second-file"/>

<target name="file-checks">
   <available file="/home/doc/somefile"  property="first.file.found"/>
   <available file="/usr/local/somefile" property="second.file.found"/>
</target>

<target name="do-something-with-first-file" if="first.file.found">
   ???
</target>

<target name="do-something-with-second-file" if="second.file.found">
   ???
</target>
Mark O'Connor
  • 76,015
  • 10
  • 139
  • 185
12

If you don't mind using ant-contrib you can take the procedural approach like this:

  <if>
    <available file="file1"/>
    <then>
      <property name="file.exists" value="true"/>
    </then>
    <else>
      <if>
        <available file="file2"/>
        <then>
          <copy file="file2" tofile="file1"/>
          <property name="file.exists" value="true"/>
        </then>
      </if>
    </else>
  </if>

Otherwise you can probably use a target that is conditional on a property being set to indicate whether the file already exists in the preferred location, like Ant task to run an Ant target only if a file exists? but using unless instead of if.

Community
  • 1
  • 1
Ben
  • 2,348
  • 2
  • 19
  • 28
  • Thanks Ben for your reply.Actually what I want to achieve is that we check both files and if the first file does not exist ie /home/doc/somefile then we can copy the second one to that directory. – user87636 Jul 14 '11 at 13:30
  • we check both files and if the first file does not exist ie /home/doc/somefile then we can copy the second one to that directory. For example . This seems not working. – user87636 Jul 14 '11 at 13:37
  • Thanks Mark and Ben. I manage to come out with a solution from the ideas I got from you guys – user87636 Jul 15 '11 at 12:11