How to read data line by line from a file using ant script?

强颜欢笑 提交于 2019-11-28 09:11:33

You can do that using the loadfile task in combination with the for task from ant-contrib (you will have to download and install ant-contrib).

<project name="test" default="compile">

  <taskdef resource="net/sf/antcontrib/antcontrib.properties">
    <classpath>
      <pathelement location="path/to/ant-contrib.jar"/>
    </classpath>
  </taskdef>

  <loadfile property="file" srcfile="somefile.txt"/>

  <target name="compile">
    <for param="line" list="${file}" delimiter="${line.separator}">
      <sequential>
        <echo>@{line}</echo>
      </sequential>
    </for>
  </target>

</project>

Just had to do that myself, actually the for + line.separator solution is flawed because :

  • it only works if the file EOLs match the platform EOL
  • it discards empty lines

Here is another (better) solution based on the previous example :

<project name="test" default="compile">

  <taskdef resource="net/sf/antcontrib/antcontrib.properties">
    <classpath>
      <pathelement location="path/to/ant-contrib.jar"/>
    </classpath>
  </taskdef>

  <loadfile property="file" srcfile="somefile.txt"/>

  <target name="compile">
    <for param="line">
      <tokens>
        <file file="${file}"/>
      </tokens>
      <sequential>
        <echo>@{line}</echo>
      </sequential>
    </for>
  </target>

</project>

The example using tokens did not work for me. In my scenario I was looking to simply print a README file while retaining the blank lines. Here is what I did.

<taskdef name="if-contrib" classname="net.sf.antcontrib.logic.IfTask" classpath="${basedir}/lib/ant/ant-contrib-1.0b3.jar" />
<taskdef name="for-contrib" classname="net.sf.antcontrib.logic.ForTask" classpath="${basedir}/lib/ant/ant-contrib-1.0b3.jar" />
<taskdef name="var-contrib" classname="net.sf.antcontrib.property.Variable" classpath="${basedir}/lib/ant/ant-contrib-1.0b3.jar" />
<target name="help">
    <for-contrib param="line">
        <tokens>
            <file file="README.txt" />
        </tokens>
        <sequential>
            <var-contrib name="line.length" unset="true" />
            <length string="@{line}" property="line.length" />
            <if-contrib>
                <equals arg1="${line.length}" arg2="0" />
                <then>
                    <echo>
                    </echo>
                </then>
                <else>
                    <echo>@{line}</echo>
                </else>
            </if-contrib>
        </sequential>
    </for-contrib>
</target>
Aniket Patil

Try This it should be work.....

<project name="test" default="compile">
 <loadfile property="file" srcfile="Help.txt"/>
   <target name="compile">
    <echo>${file}</echo> 
   </target>
</project>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!