Search code examples
apacheantpathrelative-pathabsolute-path

How to check if a path is absolute or relative?


I'm working with Apache Ant and need to check if a property holds an absolute path or relative. How can this be accomplished on Windows?

On a Unix based system, I can easily check for the the '/' int he beginning. Is there a built-in task to check this or a more generic way?


Solution

  • Since Ant 1.8.0 was released there is a feature of the property task that allows you to convert between relative and absolute paths in a portable way. In theory then, if you set a property as an absolute path from a path that is already absolute, the two should match, whereas if the first property is relative, they should differ.

    Here's an illustration:

    <property name="abs.path" value="C:\my\path" />
    <property name="rel.path" value="my\path" />
    
    <property name="abs.candidate" location="${abs.path}" relative="no" />
    <property name="rel.candidate" location="${rel.path}" relative="no" />
    
    <echo message="ABS=${abs.candidate}"/>
    <echo message="REL=${rel.candidate}"/>
    

    Result:

    Buildfile: build.xml
         [echo] ABS=C:\my\path
         [echo] REL=C:\Martin\my\path
    

    The relative="no" attribute isn't strictly needed as the default is 'no'. Note the use of location= rather than value=, so that Ant knows the path conversion should be applied.