我使用ant来替换url中的值:
<property name="dir" value="dir1, dir2, dir3" />
<property name="files" values="file1, file2, file3" />
我想在组合中替换url中的值,如dir1,file1,然后是dir2,file2,然后是dir3,file3。我循环两次替换,但不是打印三次并替换所有值,更换和打印6次。
这是我的代码:
<target name="test">
<foreach param="dirval" in="${dir}">
<foreach param="filesval" in="${files}">
<sequential>
<echo message="Testing structure: ${dirval}/${filesval}" />
</sequential>
</foreach>
</foreach>
预期输出
Testing structure: dir1/file1
Testing structure: dir2/file2
Testing structure: dir3/file3
但得到了:
Testing structure: dir1/file1
Testing structure: dir1/file2
Testing structure: dir1/file3
Testing structure: dir2/file1
Testing structure: dir2/file2
Testing structure: dir2/file3
Testing structure: dir3/file1
Testing structure: dir3/file2
Testing structure: dir3/file3
答案 0 :(得分:1)
你有这个输出的原因是你在每个3个元素的双foreach循环中,所以你循环并打印结果9次而不是所需的3次。 (foreach循环遍历dir,3次* foreach循环遍历文件,3次)(正如您在当前输出中看到的那样)
我不了解Ant,但在Java中你想要实现的目标看起来像这样。 (获得所需的结构或输出)
只使用一个循环:
string dir[] = {"dir1","dir2","dir3"};
string files[] = {"file1","file2","file3"};
for (int i = 0; i < dir.length, i++){
System.out.println("Testing structure: " + dir[i] + "/" + file[i])
}
答案 1 :(得分:0)
以下代码使用第三方Ant-Contrib library。 Ant-Contrib提供了几个允许我们模拟数组的任务:
<project name="ant-foreach-array" default="run">
<!-- Ant-Contrib provides <var>, <for>, <math>, and <propertycopy>. -->
<taskdef resource="net/sf/antcontrib/antlib.xml" />
<target name="run">
<property name="dirs" value="dir1,dir2,dir3" />
<property name="files" value="file1,file2,file3" />
<var name="fileIndex" value="1" />
<for list="${files}" delimiter="," param="file">
<sequential>
<property name="file.${fileIndex}" value="@{file}" />
<math
result="fileIndex" datatype="int"
operand1="${fileIndex}" operation="+" operand2="1"
/>
</sequential>
</for>
<var name="dirIndex" value="1" />
<for list="${dirs}" delimiter="," param="dir">
<sequential>
<propertycopy
name="fileIndex"
from="file.${dirIndex}"
override="true"
/>
<echo message="Testing structure: @{dir}/${fileIndex}" />
<math
result="dirIndex" datatype="int"
operand1="${dirIndex}" operation="+" operand2="1"
/>
</sequential>
</for>
</target>
</project>
结果:
run:
[echo] Testing structure: dir1/file1
[echo] Testing structure: dir2/file2
[echo] Testing structure: dir3/file3