How to use size of file inside Ant target

可紊 提交于 2019-12-30 20:31:13

问题


I'm currently in the process of replacing my homebrewn build script by an Ant build script.

Now I need to replace various tokens by the size of a specific file. I know how to get the size in bytes via the <length> task and store in in a property, but I need the size in kilobytes and megabytes too.

How can I access the file size in other representations (KB, MB) or compute these values from within the Ant target and store them in a property?

Edit: After I discovered the <script> task, it was fairly easy to calculate the other values using some JavaScript and add a new property to the project using project.setNewProperty("foo", "bar");.


回答1:


I found a solution that does not require any third-party library or custom tasks using the <script> task that allows for using JavaScript (or any other Apache BSF or JSR 223 supported language) from within an Ant target.

<target name="insert-filesize">
    <length file="${afile}" property="fs.length.bytes" />

    <script language="javascript">
    <![CDATA[
        var length_bytes = project.getProperty("fs.length.bytes");
        var length_kbytes = Math.round((length_bytes / 1024) * Math.pow(10,2))
                          / Math.pow(10,2);
        var length_mbytes = Math.round((length_kbytes / 1024) * Math.pow(10,2))
                          / Math.pow(10,2);
        project.setNewProperty("fs.length.kb", length_kbytes);
        project.setNewProperty("fs.length.mb", length_mbytes);
    ]]>
    </script>

    <copy todir="${target.dir}">
        <fileset dir="${source.dir}">
            <include name="**/*" />
            <exclude name="**/*.zip" />
        </fileset>
        <filterset begintoken="$$$$" endtoken="$$$$">
            <filter token="SIZEBYTES" value="${fs.length.bytes}"/>
            <filter token="SIZEKILOBYTES" value="${fs.length.kb}"/>
            <filter token="SIZEMEGABYTES" value="${fs.length.mb}"/>
        </filterset>
    </copy>
</target>



回答2:


There is a math task at http://ant-contrib.sourceforge.net/ that may be useful



来源:https://stackoverflow.com/questions/312652/how-to-use-size-of-file-inside-ant-target

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!