【问题标题】:How to read data line by line from a file using ant script?如何使用ant脚本从文件中逐行读取数据?
【发布时间】:2011-07-24 05:48:04
【问题描述】:

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

【问题讨论】:

标签: file-io ant line-by-line


【解决方案1】:

您可以将loadfile 任务与ant-contrib 中的for 任务结合使用(您必须下载并安装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>

【讨论】:

  • 我无法在我的应用程序中安装ant-contrib。你能告诉我如何只读取文件的第一行,而不使用for
  • @rajaashok 你可以在loadfile中使用headfilter
【解决方案2】:

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

  • 仅当文件 EOL 与平台 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>

【讨论】:

【解决方案3】:

使用令牌的示例对我不起作用。在我的场景中,我希望在保留空白行的同时简单地打印一个 README 文件。这就是我所做的。

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

【讨论】:

    【解决方案4】:

    试试这个应该可以的.....

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

    【讨论】:

    • 这不能回答问题
    猜你喜欢
    • 2011-12-18
    • 1970-01-01
    • 2017-12-20
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多