2011-03-28 152 views
13

在perl中,我们使用<FileDescriptor>来从文件中读取ilne的数据行。如何使用ant脚本来做同样的事情。如何使用ant脚本从文件逐行读取数据?

+0

你能给更多的环境?你想做什么? – 2011-03-28 09:17:25

+0

请参阅:http://ant.apache.org/manual/Types/filterchain.html#headfilter – 2011-03-28 13:48:29

+0

感谢@martin与筛选器和头过滤器的帮助,我能够从文件中读取数据。 – rashok 2011-03-30 18:55:56

回答

27

您可以使用loadfile任务与for任务ant-contrib(您将不得不下载并安装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> 
+0

我无法在我的应用程序中安装'ant-contrib'。你能否告诉我如何只读取文件的第一行,而不使用'for' – rashok 2011-03-28 13:49:16

+0

@rajaashok你可以使用['headfilter'](http://ant.apache.org/manual/Types/filterchain.html #headfilter)在'loadfile'里面 – lesmana 2011-03-28 13:52:35

4

就必须这样做我自己,实际上是为+ line.separator的解决方案是有缺陷的,因为:

  • 它只能如果文件EOLS匹配平台EOL
  • 它丢弃空行

这里是根据在前面的例子上的另一个(优于)溶液:

<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> 
2

使用令牌的示例对我无效。在我的方案中,我只是在保留空白行的同时打印一个自述文件。这是我做的。

<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> 
0

试试这应该是工作.....

<project name="test" default="compile"> 
<loadfile property="file" srcfile="Help.txt"/> 
    <target name="compile"> 
    <echo>${file}</echo> 
    </target> 
</project>