开发者

Ant: Create directory containing file if it doesn't already exist?

Basically, I get a path like "C:\test\subfolder1\subfolder2\subfolder3\myfile.txt", but it's possible that subfolders 1-3 don't exist already, which means I'd get an exception if I try to write to the file.

开发者_JAVA百科Is there a way to create the directory structure the target file is in, either by using some task that creates the structure when it outputs to the file and then deleting the file, or by parsing the directory part of the path and using the mkdir task first?


Ant will create the full tree of directories for you when you use the <mkdir> task. So you just need to use the <dirname> task to get the directory name from the file name.

 <dirname property="directoryProperty" file="${filePathProperty}"/>
 <mkdir dir="${directoryProperty}" />

The first line extracts the directory portion of your file path and stores it in the directoryProperty property. The second line creates the directory (and any parent directories that don't exist).


This task works well

<mkdir dir="${file}/../"/>

Sometimes we could have an alternate choice, using touch task

<touch file="${file}" mkdirs="true" verbose="true"/>

This task should do the job but would have a side effect to create the file with zero size


Just make failonerror=false to avoid the error to stop the whole logic.

<delete includeemptydirs="true" failonerror="false">
   <fileset dir="${builder-base.dir}" includes="**/*"/>
</delete>     


Using the

<mkdir dir="${dir}"/ >

inside your <target> tag should work, but I am not sure what else you want to do along with mkdir?


I'm not 100% sure it'll work but you might be able to do something like the following to make the parent directory you're after:

<mkdir dir="${file}/../"/>

If that doesn't work straight off then it might be worth defining a property using the location syntax before creating a directory with the new property: <property name="dir" location="${file}/../" />

<mkdir dir="${dir}" />


Well-behaved Ant tasks are generally expected to create any necessary directory structures unless there is a good reason not to.

Are you writing a task? If so you should add the directory creation logic to your task. If you are getting the task from a third party you should point this fact out to them and have them fix their task. Failing that Dan's solution should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜