2011-03-28 93 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>